Reputation: 57
I am using doubles to log hours for my app. My problem is I only want to record the number and the first number after the decimal place otherwise sometimes the number becomes like this (x.9000000000001) and I only need the x.9.
I have tried rounding the double value but it still has this weird extra amount of zeros.
Any way to only get the double to show the first number after decimal place.
Thanks
Upvotes: 1
Views: 1070
Reputation: 4493
The easiest way to achieve rounding to the first decimal place is to simply do the following:
let x = 4.9000000001
let roundedX = Double(round(x * 10) / 10) // roundedX = 4.9
roundedX
will be a Double
representing x
rounded to the first decimal. To get 2 decimal places, just multiply and divide by 100
instead of 10
.
Upvotes: 1