TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Help with NumberFormatter

Forums > SwiftUI

@Genka  

I am a novice programmer and do not understand with NumberFormatter I have NumberFormatter and when I enter 5540, I have it saved as 5540,00 and I need it to be 55,40, how do I need to do it correctly please help Here is my code

   var formatter: NumberFormatter {
        let formatter = NumberFormatter()
        formatter.numberStyle = .none
        formatter.maximumFractionDigits = 2
        return formatter
    }

3      

That is correct behavior. 5540 is a whole number, so there is no fractional part. 5540,00 is the correct representation with the fractional digits added.

You would need to enter 55,4 to get the NumberFormatter to output 55,40.

3      

NumberFormatter use what ever local format of number. Some use .(full stop/period/point), So I assume that your uses ,. when you enter a number 5540 this will say it a whole number therfore give 5540.00. If you enter 55,4 is will give you 55,40 but if you want to enter a number without the point then you will need to divide by 100.

3      

A small clarification: In the example of applying the formatter to a whole number such as 5540, the result would simply be 5540 without any fractional digits appended because the default value of formatter.minimumFractionDigits is 0. To display two fractional zeroes, you would have to add the statement: formatter.minimumFractionDigits = 2

4      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.