-3

I want to round up a decimal value in JavaScript. I need functionality something like below :

if decimal value is grater than or equal to 25 then i want to round up a value by plus one.

eg. if value  = 5.56789 then new value should be 6

I know using if condition it is possible.

I have done using if condition like below :

    <!DOCTYPE html>
    <html>
    <body>

    <p>Click the button to display the fixed number.</p>

    <button onclick="myFunction()">Try it</button>

    <p id="demo"></p>

    <script>
    function myFunction() {
        var num = 5.24389;
        var n = num.toFixed(2)
        var num_arr = n.split('.');
        var newval = num_arr[0];
        if(num_arr[1] >= 25)
        {
           newval++;
        }
        document.getElementById("demo").innerHTML = newval;
    }
    </script>

    </body>
    </html>

But i don't want to use any conditions.

So is there any JavaScript function which do like my example?

Any help would be appreciated!!

Legionar
  • 7,472
  • 2
  • 41
  • 70
Lalji Nakum
  • 380
  • 1
  • 14

1 Answers1

1

So the question here is how can you shift the rounding point so it is .25 instead of .50. The basic idea is you need to subtract .25 and round up to the nearest whole number.

If we are dealing with two decimal max it is simple, we subtract .24 and use ceil().

function roundUpOverQuarter(num) {
    return Math.ceil(num - .24);
}
console.log("1", roundUpOverQuarter(1));
console.log("1.24", roundUpOverQuarter(1.24));
console.log("1.25", roundUpOverQuarter(1.25));
console.log("1.5", roundUpOverQuarter(1.5));

Now the code above works with "money" value, only two decimals.To deal with greater than two decimals, it requires a bit more math. You would need to first chop it to two decimals by shifting the number up two, floor it, to drop the decimals, then shift the number back so we can follow the same process we did above.

function roundUpOverQuarter(num) {
    num = Math.floor((num*100))/100;
    return Math.ceil(num - .24);
}
console.log("1", roundUpOverQuarter(1));
console.log("1.24", roundUpOverQuarter(1.24));
console.log("1.25", roundUpOverQuarter(1.25));
console.log("1.5", roundUpOverQuarter(1.5));
console.log("1.24999", roundUpOverQuarter(1.24999));  //would fail with the first solution
epascarello
  • 204,599
  • 20
  • 195
  • 236