简体   繁体   中英

Get two digits after point for float

I have a float value as float s = 1.270001 . I need to get two digits as output ie 1.27 . But when we use %0.02f it gives output as 1.28

How to get two digits after decimal point ex: 1.16 as 1.16 only

`1.89  as 1.89` only but not `1.90`

You can do it by using NumberFormatter

let formatter = NumberFormatter()
formatter.locale = Locale.current
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.roundingMode = .floor
let stringValue = formatter.string(from:1.270001)!
print(stringValue)

Output:

1.27

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM