Reputation: 707
Is there a format specifier to format a double to only include up to a max number of non-zero significant digits after the decimal place?
For example, if I want a max of 4 significant digits and the number is:
3.14159265359, I want to display 3.1459
5.7350, I want 5.735
2.680, I want 2.68
9.200, I want 9.2
7.000, I want 7 (no decimal point)
Upvotes: 2
Views: 343
Reputation: 236410
You can use NumberFormatter
. You just need to set the maximumFractionDigits
to 4
and the minimumFractionDigits
to 0
:
let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.maximumFractionDigits = 4
nf.minimumFractionDigits = 0
nf.string(for: 3.14159265359) // "3.1416"
nf.string(for: 5.7350) // "5.735"
nf.string(for: 2.680) // "2.68"
nf.string(for: 9.200) // "9.2"
nf.string(for: 7.000) // "7"
If you would like to round down the result i.e. 3.1415
you just need to set the NumberFormatter roundingMode property to .floor
:
let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.maximumFractionDigits = 4
nf.minimumFractionDigits = 0
nf.roundingMode = .floor
nf.string(for: 3.14159265359) // "3.1415"
Upvotes: 5
Reputation: 3
This should work for you:
`let number: Float = 3.14159
let str1 = String(format: "%.2f", number) // 3.14
let str2 = String(format: "%.4f", number) // 3.1416 (rounded)
There is a really good tutorial here
Let me know if that works! This is formatting the number once it is presented as a string value.
If you are trying to actually change the number value, this was already answered on stackoverflow.
Upvotes: 0