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)
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With