Mhasan
Mhasan

Reputation: 31

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?

Upvotes: 3

Views: 431

Answers (4)

Jon Garvin
Jon Garvin

Reputation: 1188

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

Upvotes: 1

Alfonso
Alfonso

Reputation: 759

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

Upvotes: 0

Cristian Lupascu
Cristian Lupascu

Reputation: 40536

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
  2. x % (10 ** number_of_insignificant_digits) computes the insignificant part of the number
  3. subtract the value from step 2 from the initial number and now x contains the result

Here's an online test for the program: http://ideone.com/trSNOr

Upvotes: 1

Intrepidd
Intrepidd

Reputation: 20878

Here is one naive algorithm :

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

Upvotes: 3

Related Questions