简体   繁体   English

Swift:双精度/浮点数未获取十进制值

[英]Swift: Double/Float is not getting decimal values

I'm trying to get the decimals in simple division but is always returning zero:我试图用简单的除法得到小数,但总是返回零:

(lldb) po Double(20 / 100)
0.0

(lldb) po Float(20 / 100)
0.0

Any of you knows why is returning zero?你们中的任何人都知道为什么返回零? or there is a way to get the of 0.20 ?还是有办法获得0.20的?

I'll really appreciate your help我会非常感谢你的帮助

20 / 100 is an integer division, and so is 0 (since 100 > 20). 20 / 100是 integer 的除法,0 也是如此(因为 100 > 20)。 That 0 is passed to Double.init .该 0 被传递给Double.init

You want floating point division:你想要浮点除法:

20.0/100.0

You can also use 20.0/100 since a Double divided by an Int is a Double, or 20/100.0 for the same reason.您也可以使用20.0/100 ,因为 Double 除以 Int 是 Double,或者20/100.0出于同样的原因。

None of these will return 0.20 exactly, since that can't be represented by Double .这些都不会准确返回 0.20 ,因为这不能用 Double 表示 20.0/100 is 0.20000000000000001. 20.0/100是 0.20000000000000001。 But I assume this is what you're looking for.但我认为这就是你要找的。

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

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