Reputation: 31
For example,
If I have 24987654, I need it to return 24000000, is this possible?
Upvotes: 3
Views: 431
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
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
Reputation: 40536
Here's another way to do it:
x -= x % (10 ** (Math.log(x, 10).to_i - 1))
In the above statement:
Math.log(x, 10).to_i - 1
determines the number of insignificant digits to removex % (10 ** number_of_insignificant_digits)
computes the insignificant part of the numberx
contains the resultHere's an online test for the program: http://ideone.com/trSNOr
Upvotes: 1
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