圆数到最近的“第n”基于第一个非零 [英] Round number to nearest "nth" based on first non zero

查看:150
本文介绍了圆数到最近的“第n”基于第一个非零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如:

  x = 0.002341 
rounded = 0.002

x = 0.000048123
rounded = 0.00005

对于基数> 0的情况,应该执行

  x = 1.000234 
rounded = 1.0002

我知道我可以使用 Double(round(1000 * x)/ 1000)如果我知道数字,但我希望它可以工作任何数字。有一个快速的功能吗?

解决方案

你可以用对数有一点乐趣来解决这个问题:

  func roundFirst(x:Double) - >双{
如果x == 0 {
return x;
}
let mul:Double = pow(10,floor(log10(abs(x))))
return round(x / mul)* mul
}

log10(abs(x))的非小数部分给你一个正数或负数的十个数字的倒数,你用作乘数。 floor 删除分数, pow(10,...)给你一个乘数,用于你的四舍五入



我在操场上尝试了几个数字。这是我所得到的:

  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


I want to round a Double to the nearest non zero number that follows the decimal.

For example:

x = 0.002341
rounded = 0.002

x = 0.000048123
rounded = 0.00005

For cases where the base number is > 0, it should perform as such

x = 1.000234
rounded = 1.0002

I know I can use Double(round(1000*x)/1000) if I know the number of digits, but I want it to work for any number. Is there a swift function that does this?

解决方案

You can have a little fun with logarithms to 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 you a positive or negative power of ten of the inverse of the number which you use as your multiplier. floor drops the fraction, and pow(10,...) gives you a multiplier to use in your rounding trick.

I tried this in the playground with a few numbers. Here is what 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

这篇关于圆数到最近的“第n”基于第一个非零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆