在Swift中从String转换为Decimal时,decimal值会被删除 [英] Decimal values get remove when convert from String to Decimal in Swift
问题描述
请检查此示例
let strValue = "12.00"
let decimalValue = Decimal(string: strValue) // 12
它总是返回12而不是12.00
我也尝试使用NSNumber
,Float
和Double
,但是它总是删除零.
it always returns 12 not 12.00
I also try with NSNumber
, Float
, and Double
but it always remove zeros.
您能先谢谢我吗?
推荐答案
就像马丁说的那样. 12和12.00是相同的数字.逗号后面有多少个0并不重要.
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.
字符串(格式:%.6f",12)将给出12.000000作为字符串.
String(format: "%.6f", 12) will give 12.000000 as String.
小数是结构.数字的含义保持不变.扔到操场上.
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)
看到了吗?数学中没有无限0这样的东西.零是有限的.从12000000开始的小数和从12开始创建的小数是相同的.
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.
这篇关于在Swift中从String转换为Decimal时,decimal值会被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!