Search code examples
javascriptroundingfloor

How to round down decimal number in javascript


I have this decimal number: 1.12346

I now want to keep only 4 decimals but I want to round down so it will return: 1.1234. Now it returns: 1.1235 which is wrong.

Effectively. I want the last 2 numbers: "46" do round down to "4" and not up to "5"

How is this possible to do?

    var nums = 1.12346;
    nums = MathRound(nums, 4);
    console.log(nums);

function MathRound(num, nrdecimals) {
    return num.toFixed(nrdecimals);
}


Solution

  • If you're doing this because you need to print/show a value, then we don't need to stay in number land: turn it into a string, and chop it up:

    let nums = 1.12346;
    
    // take advantage of the fact that
    // bit operations cause 32 bit integer conversion
    let intPart = (nums|0); 
    
    // then get a number that is _always_ 0.something:
    let fraction = nums - intPart ;
    
    // and just cut that off at the known distance.
    let chopped = `${fraction}`.substring(2,6);
    
    // then put the integer part back in front.
    let finalString = `${intpart}.${chopped}`;
    

    Of course, if you're not doing this for presentation, the question "why do you think you need to do this" (because it invalidates subsequent maths involving this number) should probably be answered first, because helping you do the wrong thing is not actually helping, but making things worse.