6

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!

0

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.