Swift中数字的小数位数

在下面的代码中,我根据一些Toggles是true还是false,通过累加不同的值来声明变量。当我尝试打印此变量时,它返回一个数字和一个十进制的小数,但之后紧跟着很多0。有没有办法在数字后不显示零?

免责声明我正在使用Swift Playground

var rvalues = [6.5, 5.9, 5.3, 4.8, 4.2, 3.5, 3.1, 2.9, 1.75, 1.5, 1.2, 1.05, 0.92, 0.82, 0.75, 0.7]


var r0 : Double {
        model.rvalues[(model.wearingMaskToggle ? 1:0) + (model.washingHandsToggle ? 2:0) + (model.quarantineToggle ? 8:0) + (model.coverMouthToggle ? 4:0)]
    }
评论
ysunt
ysunt

First, if you are curious where those 0 come from, read is floating point math broken? - a lot of the values in your array aren't precisely representable as Doubles.

To solve your display problem, use a NumberFormatter with minimumFractionDigits and maximumFractionDigits set appropriately.

Alternatively, use Decimal to represent your values.

点赞
评论