使用NumberFormatter将字符串转换为数字未返回预期的数字。

huangapple go评论63阅读模式
英文:

Convert string to number using NumberFormatter not returning expected number

问题

let formatter = NumberFormatter()
let sample1 = formatter.number(from: "29.99") ---> 29.99
let sample2 = formatter.number(from: "79.99") ---> 79.98999999999999

But I expect to get 79.99 as the result of sample2

Tried using different rounding modes with no help

英文:
let formatter = NumberFormatter()
let sample1 = formatter.number(from: "29.99") ---> 29.99
let sample2 = formatter.number(from: "79.99") ---> 79.98999999999999

But I expect to get 79.99 as the result of sample2

Tried using different rounding modes with no help

答案1

得分: 0

这是因为一个浮点数。您可以在这里查看什么是FPN。

如果您需要四舍五入到2位小数,您可以使用此扩展链接

extension NSNumber {
    func rounded(to decimalPlaces: Int) -> Double {
        let multiplier = pow(10, Double(decimalPlaces))
        return (Double(truncating: self) * multiplier).rounded(.toNearestOrEven) / multiplier
    }
}

let sample1 = formatter.number(from: "29.99")?.rounded(to: 2) --> 将是 Optional(29.99)
let sample2 = formatter.number(from: "79.99")?.rounded(to: 2) --> 将是 Optional(79.99)
英文:

This happens because a Floating Point Number. You can see what is FPN in here

If you need 2 decimal value with round , you can use this extension link

extension NSNumber {
    func rounded(to decimalPlaces: Int) -> Double {
        let multiplier = pow(10, Double(decimalPlaces))

    return (Double(truncating: self) * multiplier).rounded(.toNearestOrEven) / multiplier
    }
}

  let sample1 = formatter.number(from: "29.99")?.rounded(to: 2) --> will be Optional(29.99)
  let sample2 = formatter.number(from: "79.99")?.rounded(to: 2) --> will be Optional(79.99)

huangapple
  • 本文由 发表于 2023年3月7日 18:37:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75660869.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定