Search code examples
swiftdecimalswift-playground

Number of decimals in a number in Swift


In the code below, I declared a variable by adding up different values depending on if some Toggles are true or false. When I try and print this variable it returns with a number and a single decimal after but it then is followed by a lot of 0 after it. Is there a way to display no zeros after the number?

Disclaimer I am using 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)]
    }

Solution

  • 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.