-4

I wish to save some Double to an array, and I just need to have 2 decimal places Double. So I rounded the origin double to 2 decimal places, and when I print the rounded Double, the result is correct. However when I save these Double to an array and print the Double, the result becomes many decimal place.

What should I do to force only 2 decimal Double in the array?

For example:

Double -> 2.344563343534   // Original value 

rounded -> 2.35            // Rounded value I want

After I save the rounded Double to array and print:

Double in array -> 2.34444444444444   // I hope this value only in 2 decimal place.
chirag90
  • 2,211
  • 1
  • 22
  • 37
mmk
  • 207
  • 4
  • 7
  • If it _must_ be only 2 decimals you are probably better of with strings but given the result you get the issue is probably something else than rounding, pleas share your code. – Joakim Danielson Sep 12 '19 at 12:31

1 Answers1

2

Convert the Double to String upto 2 decimal places as per requirement.

let num = 2.344563343534
let str = String(format: "%.2f", num)
print(str) //"2.34"

Now, get the Double from str,

let doubleValue = Double(str)
print(doubleValue) //2.34
PGDev
  • 23,751
  • 6
  • 34
  • 88
  • If the goal is precision better to use a Decimal to represent it properly – Leo Dabus Sep 12 '19 at 12:42
  • Thanks guys for all your answers. In my case, round to 2 decimal place is precise enough. I will use @PGDev's solution, and that's the only solution so far I can think of. And use Decimal is a good idea as well, but I need Double data type, because I will encode these data into JSON file later. – mmk Sep 12 '19 at 14:13