ACR
ACR

Reputation: 185

Rounding numbers in swift

In Swift, I need to be able to round numbers based on their value. If a number is whole, which just ".0" after it, I need to convert it to an integer, and if the number has digits after the decimal that is greater than 2 digits, I need to round it to 2 digits.

For example:

1.369352 --> 1.37
7.75     --> 7.75  
2.0      --> 2  

How can I check my numbers and round them according to these rules?

Upvotes: 2

Views: 1284

Answers (2)

Patronics
Patronics

Reputation: 1389

this function returns a string of the result needed.

func roundnumber(roundinput:Double) ->String{
var roundoutputint=0
var roundoutputfloat=0.0
if (roundinput - floor(roundinput) < 0.00001) { // 0.000001 can be changed depending on the level of precision you need
    //integer

    roundoutputint = Int(round(roundinput))
    return String(roundoutputint)
}
else {
    //not integer
    //roundoutputfloat=round(10 * roundinput) / 10
    return String(format:"%.2f",roundinput)
}
}

for example:

roundnumber(1.3693434) //returns "1.37"
roundnumber(7.75)     //returns "7.75"
roundnumber(2.0)      // returns "2"

Upvotes: 1

Mark
Mark

Reputation: 12565

Something like this should be good?

func formatNumber (number: Double) -> String? {

    let formatter = NSNumberFormatter()
    formatter.maximumFractionDigits = 2

    let formattedNumberString = formatter.stringFromNumber(number)
    return formattedNumberString?.stringByReplacingOccurrencesOfString(".00", withString: "")

}

formatNumber(3.25) // 3.25
formatNumber(3.00) // 3
formatNumber(3.25678) // 3.26

Upvotes: 5

Related Questions