将浮点数限制为小数点后两位,并为Swift中的数字提供逗号分隔格式

时间:2018-12-27 07:17:05

标签: ios swift rounding

我在将Float数限制为两位小数时遇到问题,并且在Swift中也提供了逗号分隔的结果。我尝试了以下代码:

var myNum = 99.999999
myNum = (myNum * 100).rounded() / 100
print(myNum)
//Result : 100.0, Required_Result : 99.99



let formatted = String(format: "myNum: %.2f", myNum)
//Result : 100.00, Required_Result : 99.99

例如:1234.99999的结果应为1,234.99

为了使用逗号分隔并截断到小数点后两位:

 let numberFormatter = NumberFormatter()
 numberFormatter.maximumFractionDigits = 2
 numberFormatter.numberStyle = NumberFormatter.Style.decimal
 let formattedNumber = numberFormatter.string(from: NSNumber(value: number))
 return formattedNumber!

上面的代码给出以下结果: 编号:9999.9984 结果:1,000.0 所需结果:9,999.99

3 个答案:

答案 0 :(得分:2)

使用NSNumberFormatter并相应地配置其舍入模式:

    let formatter = NumberFormatter()
    formatter.maximumFractionDigits = 2
    formatter.roundingMode = .down
    let s = formatter.string(from: 99.99999)
    print(s as Any) //99.99

答案 1 :(得分:2)

这是您需要使用NumberFormatter解决此问题的解决方案

var myNum = 9999.9998
myNum = (myNum * 100.0) / 100.0
print(myNum)

let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .decimal
currencyFormatter.maximumFractionDigits = 2
currencyFormatter.minimumFractionDigits = 2
currencyFormatter.roundingMode = .down
let s = currencyFormatter.string(from: NSNumber.init(value: myNum)) // NSNumber init with double
print(s ?? "0.0")

答案 2 :(得分:1)

为了获得更高的精度,您可以使用Swift标准库中的Float80

像这样使用它,您将获得9,999.99的结果:

let myNum = 9999.9998
let floaNumber = Float80(Int(myNum*100))
let result = Double(floaNumber/100.0)
print(result)

let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal

let formattedNumber = numberFormatter.string(from: NSNumber(value: result))
print(formattedNumber!)