简体   繁体   English

在 Swift 中从字符串转换为十进制时,十进制值会被删除

[英]Decimal values get remove when convert from String to Decimal in Swift

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.它总是返回 12 而不是 12.00 我也尝试使用NSNumberFloatDouble但它总是删除零。

Can you please help me with this thanks in advance你能帮我解决这个问题吗?

Like martin said.就像马丁说的。 12 and 12.00 is the same number. 12 和 12.00 是同一个数字。 It doesn't mathematical matter how many 0 are behind the comma.逗号后面有多少个 0 无关紧要。

While a number stays the same, the representation is a different topic.虽然数字保持不变,但表示是不同的主题。

String(format: "%.6f", 12) will give 12.000000 as String. String(format: "%.6f", 12) 将给出 12.000000 作为字符串。

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.数学中没有无限0这样的东西。 Zero is finite.零是有限的。 A Decimal from 12.000000 and a Decimal created from 12 are the same.来自 12.000000 的小数和从 12 创建的小数是相同的。

在此处输入图片说明

There is no difference between 12 & 12.00 . 1212.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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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