Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an efficient way to round a float to the nearest hundredths place in swift?

Tags:

ios

swift

I would like to round a float in swift but everything I have found tells you to convert it in a string. Is there a way to convert the float itself?

Example: 14.14910001 -> 14.15

like image 305
Sam Kirkiles Avatar asked Dec 20 '22 07:12

Sam Kirkiles


1 Answers

You can use round() with a "scale factor" of 100:

let x = 14.14910001
let y = round(100.0 * x) / 100.0
println(y) // 14.15

But you should note that a binary floating number cannot represent a number like 14.15 exactly, so this will give the nearest Double approximation of 14.15.

like image 100
Martin R Avatar answered Dec 24 '22 02:12

Martin R