-1

All my values are being returned from the server as 3 decimal places. I need to round to the nearest 10, 2 decimal places, ex. decimal(18,2) from decimal(18,3). The catch is that when it's a 5, it needs to round down.

I need to do this in JavaScript :D

I can not guarantee 3 decimal places will be returned, that is the maximum.

ex. 4.494 -> 4.49

**ex. 4.495 -> 4.49**

ex. 4.496 -> 4.50
Jake Steele
  • 498
  • 3
  • 14
  • have you tried anything? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round, `if(Math.abs(num) === 5)` + `Math.floor` should cover your case of the number being 5 – Rob M. Oct 09 '14 at 01:30

2 Answers2

1

It seems you want special rounding only where the last digit is 5, so test for that and round those cases differently:

function myRound(n) {

  // If ends in .nn5, round down
  if (/\.\d\d5$/.test(''+n)) {
    n = Math.floor(n*100)/100;
  }

  // Apply normal rounding
  return n.toFixed(2);
}

console.log(myRound(4.494));  // 4.49
console.log(myRound(4.495));  // 4.49
console.log(myRound(4.496));  // 4.50
RobG
  • 142,382
  • 31
  • 172
  • 209
0

Perhaps create your own custom round function? check out Is it ok to overwrite the default Math.round javascript functionality?

Given the solution in the above post, you might modify it slightly like this:

Number.prototype.round = function(precision) {
    var numPrecision = (!precision) ? 0 : parseInt(precision, 10);
    var numBig = this * Math.pow(10, numPrecision);
    var roundedNum;
    if (numBig - Math.floor(numBig) == 0.5)
        roundedNum = (Math.round(numBig) + 1) / Math.pow(10, numPrecision);
    else
        roundedNum = Math.round(numBig) / Math.pow(10, numPrecision);

    return roundedNum;
};

var n = 2.344;
var x = n.round(2);

alert(x);
Community
  • 1
  • 1
Derek
  • 11
  • 2