Round function doesn't work as expected

455 Views Asked by At

I'm trying round a Double value with two decimal places:

var x = 0.68999999999999995 var roundX = round(x * 100.0) / 100.0 println(roundX) // print 0.69

If print the value is correct.. but the var value isn't that i expect, continue 0.68999999999999995

enter image description here

I need the Double value... not String like other StackOverflow answers :(

1

There are 1 best solutions below

1
On BEST ANSWER

Floating point numbers like doubles do not have a number of decimal places. They store values in binary, and a value like .69 can't be represented exactly. It's just the nature of binary floating point on computers.

Use a number formatter, or use String(format:) as @KRUKUSA suggests

var x:Double = 0.68999999999999995
let stringWithTwoDecimals = String(format: "%.2f", x)
println(stringWithTwoDecimals)