round to nearest .25 javascript

孤街浪徒 提交于 2019-12-17 18:04:29

问题


I want to convert all numbers to the nearest .25

So...

5 becomes 5.00
2.25 becomes 2.25
4 becomes 4.00
3.5 becomes 3.50

Thanks


回答1:


Here’s an implementation of what rslite said:

var number = 5.12345;
number = (Math.round(number * 4) / 4).toFixed(2);



回答2:


Multiply by 4, round to integer, divide by 4 and format with two decimals.

Edit Any reason for the downvotes? At least leave a comment to know what should be improved.




回答3:


If speed is your concern, note that you can get about a 30% speed improvement by using:

var nearest = 4;
var rounded = number + nearest/2 - (number+nearest/2) % nearest;

From my website: http://phrogz.net/round-to-nearest-via-modulus-division
Performance tests here: http://jsperf.com/round-to-nearest




回答4:


Here is a generic function to do rounding. In the examples above, 4 was used because that is in the inverse of .25. This function allows the user to ignore that detail. It doesn't currently support preset precision, but that can easily be added.

function roundToNearest(numToRound, numToRoundTo) {
    numToRoundTo = 1 / (numToRoundTo);

    return Math.round(numToRound * numToRoundTo) / numToRoundTo;
}



回答5:


Here is @Gumbo's answer in a form of a function:

var roundNearQtr = function(number) {
  return (Math.round(number * 4) / 4).toFixed(2);
};

You can now make calls:

roundNearQtr(5.12345); // 5.00
roundNearQtr(3.23); // 3.25
roundNearQtr(3.13); // 3.25
roundNearQtr(3.1247); // 3.00



回答6:


function roundToInc(num, inc) {
    const diff = num % inc;
    return diff>inc/2?(num-diff+inc):num-diff;
}

> roundToInc(233223.2342343, 0.01)
233223.23
> roundToInc(505, 5)
505
> roundToInc(507, 5)
505
> roundToInc(508, 5)
510



回答7:


A very good approximation for rounding:

function Rounding (number, precision){

  var newNumber;
  var sNumber = number.toString();

  var increase = precision + sNumber.length - sNumber.indexOf('.') + 1;

  if (number < 0)
    newNumber = (number -  5 * Math.pow(10,-increase));
  else
  newNumber = (number +  5 * Math.pow(10,-increase));

  var multiple = Math.pow(10,precision);
  return Math.round(newNumber * multiple)/multiple;
}



回答8:


Use below function, hope it helps

function roundByQuarter(value) {
    var inv = 1.0 / 0.25;
    return Math.round(value * inv) / inv;
}

Call the function as below, will result the nearest Quarter value, that is it will not return .32, .89, .56 but will return .25, .75, .50 decimals only.

roundByQuarter(2.74) = 2.75

roundByQuarter(2.34) = 2.25

roundByQuarter(2.94) = 3.00

roundByQuarter(2.24) = 2.25


来源:https://stackoverflow.com/questions/1553704/round-to-nearest-25-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!