-1

How to round off nearest integer after decimal.If the value after decimal above .25 than it should round of .50. It means the result should be 14.50 and if the result 14.25 or under than it should be only 14. Please check examples

document.getElementById("total1").innerHTML =(Math.ceil(501/500)*3.60*2).toFixed(2);

document.getElementById("total2").innerHTML =(Math.ceil(500/500)*3.60*2).toFixed(2);
<b>Result 1: (above 25)</b> 
<div id="total1"></div>
<br>
<b>Expected Result 1:</b>
14.50
<br>
<br>

<b>Result 2: (below 25)</b> 
<div id="total2"></div>
<br>
<b>Expected Result 2:</b>
14
<br>
<p>If the value after decimal above .25 than it should round of .50. It means the result should be 14.50 and if the result 14.25 or under than it should be only 14.</p>
Taha Farooqui
  • 637
  • 10
  • 25

3 Answers3

2

You can use this function to round your numbers also to +0.5.

function roundToDecimal(number) {
    let num = {
        int: Math.floor(number),
        dec: number - Math.floor(number)
    };
    if (num.dec < 0.25) {
        return num.int;
    }  else if (num.dec < 0.75) {
        return num.int + 0.5;
    } else {
        return num.int + 1;
    }
}

console.log(roundToDecimal(14.40));
smunteanu
  • 422
  • 3
  • 9
2

A faster way of rounding a number also to +0.5 is by rounding the number multiplied by 2, and then divide the result by 2 as well.

function roundToDecimal(number) {
    return Math.round(number * 2) / 2;
}

console.log(roundToDecimal(14.40));
smunteanu
  • 422
  • 3
  • 9
0

Multiply the value by 2, then round it. afterwards divide through 2. With this you have raounded on x.50 and x.00.

document.getElementById("total").innerHTML = ((Math.round((Math.ceil(501/500))*3.60*4))/2).toFixed(2);
<b>Result:</b> 
<div id="total"></div>
<br>
<b>Expected Result:</b>
14.50
<br>
<p>If the value after decimal equal or above .25 than it should round of .50. It means the result should be 14.50 and if the result 14.25 than it should be only 14.</p>
Sascha
  • 4,576
  • 3
  • 13
  • 34
  • 1
    @Ivar - Yes you are right, I corrected it. I had a fault in it + question is not complete because the OP deleted previous his question it and creates a new one. But with the new one we have not all informations here. The price is the fee for 2 years. – Sascha Aug 30 '20 at 21:14