user4882614
user4882614

Reputation:

How to round a double to the nearest hundredth in Swift?

I am making an app, which takes one number usually something like 10.00 or 100.00 and multiplies it by 0.15 or 0.20 and outputs it to a Label.

What ends up happening in some situations is the answer comes out to be 2.3234342, notice all the numbers after the decimal, which I don't want.

I want Swift automatically round up to the nearest hundredth or keep hundredth the same and then delete everything after the hundredth.

I want the code to automatically determine whether it will round up or keep the number the same.

Upvotes: 2

Views: 5758

Answers (2)

beyowulf
beyowulf

Reputation: 15331

someFloat+=0.005
label.Text = String(format: "a float number: %.02f ", someFloat))

Upvotes: 3

user3432164
user3432164

Reputation:

You can use round() with a "scale factor" of 1000:

let x = 14.14910001
let y = round(1000.0 * x) / 1000.0
println(y)

May be it will help you.

Upvotes: 3

Related Questions