I have the value 25.00 in a float
How can I display the value with x number before dot.
Number after dot can be format with "%.xf" (x is number after dot)
But how can i print like this with "%4.2f"
25.00 -> 0025.00
123.12 -> 0123.12
Asked
Active
Viewed 626 times
0
-
1FYI - Look into `NSNumberFormatter` instead of using a string format. This will give better output based on the user's locale. – rmaddy Jan 09 '16 at 04:56
-
Check my answer for this https://stackoverflow.com/questions/16332849/is-there-any-easy-way-to-round-a-float-with-one-digit-number-in-objective-c/47348309#47348309 it will help you. – Chandni Nov 17 '17 at 10:20
1 Answers
3
Use a format string like this: %07.2f
where 7
is the total length of the output (including the decimal point) and 2
is the number of digits after the decimal. The 0
causes leading zeros to be used to pad the number (instead of spaces).
let str1 = NSString(format: "%07.2f", 25.00) // str1 = "0025.00"
let str2 = NSString(format: "%07.2f", 123.12) // str2 = "0123.12"

Marc Khadpe
- 2,012
- 16
- 14
-
Should mention that the `0` in the format means that the value will be padded with zeros to fill an remaining space. Without the `0` the extra room will be filled with spaces. – rmaddy Jan 09 '16 at 04:55