3

For example,

If I have 24987654, I need it to return 24000000, is this possible?

Oto Brglez
  • 4,113
  • 1
  • 26
  • 33
Mhasan
  • 31
  • 1

4 Answers4

3

Here is one naive algorithm :

n = 24987654
n / (10 ** (n.to_s.size - 2)) * (10 ** (n.to_s.size - 2)
=> 24000000
Intrepidd
  • 19,772
  • 6
  • 55
  • 63
  • you probably meant `n.to_s.size` instead of `n.size` – Cristian Lupascu Mar 20 '13 at 22:09
  • I'm using MRI 2.0.0, let me check with 1.9.3 – Intrepidd Mar 20 '13 at 22:11
  • 2
    Ok, on my machine (64 bits), integers size is 8 bytes, didn't bother to check with another integer that the one provided in the example, that is 8 characters long, nice coincidence, I guess you're on a 32 bits machine. I thought Fixnum#size will return the number of chars, my bad. – Intrepidd Mar 20 '13 at 22:13
1

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

Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137
1
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
Jon Garvin
  • 1,178
  • 9
  • 26
0

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

Alfonso
  • 758
  • 5
  • 8