Rounding to nearest 100

前端 未结 7 814

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 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.

提交回复
热议问题