2

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.

  • Bhumica hads explained how to round to a certain number of digits. BUT it is extremely likely that what you are looking for is string formatting, simply using NSString,, which is very easy to use. [Example](http://stackoverflow.com/a/24052438/294884) – Fattie Nov 02 '15 at 12:39
  • @JoeBlow YES you are right you can use that way also. –  Nov 02 '15 at 13:17
  • 1
    Right. it's just possible the OP "actually" wants a number of two digits (for example, for some gaming use) but it's very likely the OP just wants to use String/format. Cheers! – Fattie Nov 02 '15 at 13:38

2 Answers2

3

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.

3
someFloat+=0.005
label.Text = String(format: "a float number: %.02f ", someFloat))
beyowulf
  • 15,101
  • 2
  • 34
  • 40