简体   繁体   English

在 Ruby 中,如何将数字四舍五入为 2 位有效数字

[英]In Ruby how do you round down a number to 2 significant digits

For example,例如,

If I have 24987654, I need it to return 24000000, is this possible?如果我有 24987654,我需要它返回 24000000,这可能吗?

Here is one naive algorithm :这是一种天真的算法:

n = 24987654
n / (10 ** (n.to_s.size - 2)) * (10 ** (n.to_s.size - 2)
=> 24000000

Here's another way to do it:这是另一种方法:

x -= x % (10 ** (Math.log(x, 10).to_i - 1))

In the above statement:在上述声明中:

  1. Math.log(x, 10).to_i - 1 determines the number of insignificant digits to remove Math.log(x, 10).to_i - 1确定要删除的无意义数字的数量
  2. x % (10 ** number_of_insignificant_digits) computes the insignificant part of the number x % (10 ** number_of_insignificant_digits)重要x % (10 ** number_of_insignificant_digits)计算数字的无意义部分
  3. subtract the value from step 2 from the initial number and now x contains the result从初始数字中减去第 2 步的值,现在x包含结果

Here's an online test for the program: http://ideone.com/trSNOr这是该程序的在线测试: http : //ideone.com/trSNOr

n = 24987654
n.round((n.to_s.size - 2)*-1) #=> 25000000
n.ceil((n.to_s.size - 2)*-1) #=> 25000000
n.floor((n.to_s.size - 2)*-1) #=> 24000000

n = 24187654
n.round((n.to_s.size - 2)*-1) #=> 24000000
n.ceil((n.to_s.size - 2)*-1) #=> 25000000
n.floor((n.to_s.size - 2)*-1) #=> 24000000

Just another way:只是另一种方式:

n = 24987654
a = n.to_s[0, 2] + '0' * ((a.to_s.length)-2)

Will output the string:将输出字符串:

=> "24000000"

You can convert it as integer calling the .to_i method您可以调用.to_i方法将其转换为整数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM