Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying .0 after round numbers in Swift [duplicate]

I’ve made a calculator using Doubles in Swift. The problem is that when I display the outcome it will display .0 at the end even if it’s a round number. I have tried the round() function but since it’s a double it still seems to always display .0 . In Objective-c i did this by typing:

[NSString stringWithFormat:@”%.0f”, RunningTotal]; //RunningTotal being the outcome

In this case there would be no decimals at all which there would if there stood @”%.3f” for example.

Does anyone know how to do this in swift? I’ve looked around on different forums but couldn’t find it anywhere... Thanks!

like image 661
Mats Avatar asked Oct 29 '14 18:10

Mats


1 Answers

Your can do the same in Swift.

let runningTotal = 12.0
let string = String(format:"%.0f", runningTotal)
println(string) // Output: 12

Generally, this would round the floating point number to the next integer.

The %g format could also be used, because that does not print trailing zeros after the decimal point, for example:

String(format:"%g", 12.0) // 12
String(format:"%g", 12.3) // 12.3

For more advanced conversions, have a look at NSNumberFormatter.

like image 72
Martin R Avatar answered Sep 28 '22 16:09

Martin R