-3

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)]
    }
Asperi
  • 228,894
  • 20
  • 464
  • 690
Elias Fizesan
  • 265
  • 1
  • 3
  • 18

1 Answers1

4

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.

Gereon
  • 17,258
  • 4
  • 42
  • 73
  • Using Decimal does not work I get the error "Cannot convert return expression of type 'Double' to return type 'Decimal'" – Elias Fizesan May 17 '20 at 19:50
  • Of course this works in Playgrounds. When you do change your representation to Decimals in `rvalue`, you'll have to change `r0` as well as there's not automatic conversion. – Gereon May 17 '20 at 20:32
  • How do I change the representation, is it just rvalues: Decimal – Elias Fizesan May 17 '20 at 20:49
  • no, `[Decimal]`. You'll also have to make sure you're not initializing your array with precise values. – Gereon May 18 '20 at 10:08