Rounding to nearest 100

前端 未结 7 807

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 :-)

相关标签:
7条回答
  • 2020-12-15 04:57

    Is this homework?

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

    0 讨论(0)
  • 2020-12-15 04:58

    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.

    0 讨论(0)
  • 2020-12-15 05:00

    Ruby's round method can consume negative precisions:

    n.round(-2)

    In this case -2 gets you rounding to the nearest hundred.

    0 讨论(0)
  • 2020-12-15 05:01
    100 * round(n/100.0)
    
    0 讨论(0)
  • 2020-12-15 05:02

    As per Pawan Pillai's comment above, rounding to nearest 100th in Javascript:
    100 * Math.floor((foo + 50) / 100);

    0 讨论(0)
  • 2020-12-15 05:10

    I know it's late in the game, but here's something I generally set up when I'm dealing with having to round things up to the nearest nTh:

    Number.prototype.roundTo = function(nTo) {
        nTo = nTo || 10;
        return Math.round(this * (1 / nTo) ) * nTo;
    }
    console.log("roundto ", (925.50).roundTo(100));
    
    Number.prototype.ceilTo = function(nTo) {
        nTo = nTo || 10;
        return Math.ceil(this * (1 / nTo) ) * nTo;
    }
    console.log("ceilTo ", (925.50).ceilTo(100));
    
    Number.prototype.floorTo = function(nTo) {
        nTo = nTo || 10;
        return Math.floor(this * (1 / nTo) ) * nTo;
    }
    console.log("floorTo ", (925.50).floorTo(100));
    

    I find myself using Number.ceilTo(..) because I'm working with Canvas and trying to get out to determine how far out to scale.

    0 讨论(0)
提交回复
热议问题