ios - Round number to nearest "nth" based on first non zero -
i want round double nearest non 0 number follows decimal.
for example:
x = 0.002341 rounded = 0.002 x = 0.000048123 rounded = 0.00005
for cases base number > 0, should perform such
x = 1.000234 rounded = 1.0002
i know can use double(round(1000*x)/1000)
if know number of digits, want work number. there swift function this?
you can have little fun logarithms solve this:
func roundfirst(x:double) -> double { if x == 0 { return x; } let mul : double = pow(10, floor(log10(abs(x)))) return round(x/mul)*mul }
the non-fractional part of log10(abs(x))
gives positive or negative power of ten of inverse of number use multiplier. floor
drops fraction, , pow(10,...)
gives multiplier use in rounding trick.
i tried in playground few numbers. here i've got:
println(roundfirst(0.002341)) // 0.002 println(roundfirst(0.000048123)) // 5e-05 println(roundfirst(0.0)) // 0.0 println(roundfirst(2.6)) // 3.0 println(roundfirst(123.0)) // 100 println(roundfirst(-0.002341)) // -0.002 println(roundfirst(-0.000048123)) // -5e-05 println(roundfirst(-2.6)) // -3.0 println(roundfirst(-123.0)) // -100
Comments
Post a Comment