Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round a digit upto two decimal place in Swift

Tags:

ios

swift4

I'm getting a value of digits which i'm trying to convert to two decimal places. But when i convert it it makes the result to 0.00 . The digits are this 0.24612035420731018 . When get its .2f value it shows 0.00. The code that i tried is this,

 let  digit = FindResturantSerivce.instance.FindResModelInstance[indexPath.row].distance
    let text = String(format: "%.2f", arguments: [digit])
    print(text)
like image 349
Hamza Avatar asked Feb 27 '18 16:02

Hamza


People also ask

Can you round a whole number to 2 decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

How do you round off numbers in Swift?

Swift provide a built-in function named as ceil() function. This function is used to round the given number to the nearest smallest integer value which is greater than or equal to the given number.

How do I set precision in Swift?

If you'd like to interpolate a float or a double with a String in Swift, use the %f String format specifier with appropriate number in order to specify floating point precision. Note that Swift automatically rounds the value for you.


1 Answers

If you want to really round the number, and not just format it as rounded for display purposes, then I prefer something a little more general-purpose:

extension Double {
    func rounded(digits: Int) -> Double {
        let multiplier = pow(10.0, Double(digits))
        return (self * multiplier).rounded() / multiplier
    }
}

So you can then do something like:

let foo = 3.14159.rounded(digits: 3) // 3.142
like image 136
drewster Avatar answered Oct 02 '22 20:10

drewster