Convert String to Decimal number it remove points before zeros in Swift 4

爷,独闯天下 提交于 2019-12-13 08:31:03

问题


Please check this example

 let strValue = "12.00"
 let decimalValue = Decimal(string: strValue) // 12

it always returns 12 not 12.00 I also try with NSNumber, Float, and Double but it always remove zeros.

Can you please help me with this thanks in advance


回答1:


Like martin said. 12 and 12.00 is the same number. It doesn't mathematical matter how many 0 are behind the comma.

While a number stays the same, the representation is a different topic.

String(format: "%.6f", 12) will give 12.000000 as String.

Edit:
A Decimal is a Struct. The meaning of the numbers stays the same. Throw this in a playground.

import UIKit
let decimal = Decimal(12.0000000000)
let justAnInt = 12

let sameDecimal = decimal == Decimal(justAnInt)

See? There is no such thing as infinite 0 in math. Zero is finite. A Decimal from 12.000000 and a Decimal created from 12 are the same.




回答2:


There is no difference between 12 & 12.00. The only thing we need is to present the value to user., for that you could use formatted string.

Like:

String(format: "%.2f", floatValue)


来源:https://stackoverflow.com/questions/56004505/convert-string-to-decimal-number-it-remove-points-before-zeros-in-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!