Friday, April 8, 2011

Rounding to nearest 100

First number needs to be rounded to nearest second number. There are many ways of doing this, but whats the best and shortest algorithm? Anyone up for a challenge :-)

1244->1200
1254->1300
123->100
178->200
1576->1600
1449->1400
123456->123500
654321->654300
23->00
83->100

From stackoverflow
  • Is this homework?

    Generally, mod 100, then if >50 add else subtract.

    Senthoor : No its not home work :-)
    John Leidegren : What the hell Brian! mod and if-then-else that's gonna be really slow. If you're using integers check David's answer. It's a branch-less common way to solve this problem. It works with floating-point numbers as well.
    Senthoor : I myself came up with this answer in Ruby. numbers.each {|number| puts number + '->' + number.gsub(/\d\d\d$/,(number[number.size-3,1].to_i + number[number.size-2,1].to_i / 5).to_s+'00')}
  • For input n:

    (n + 50) / 100 * 100
    

    using integer division.

    Note that many languages/libraries already have functions to do this.

  • This will do it, given you're using integer math:

    n = (n + 50) / 100 * 100
    

    Of course, you didn't specify the behavior of e.g., 1350 and 1450, so I've elected to round up. If you need round-to-even, that'll not work.

  • 100 * round(n/100.0)
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.