Rounding a decimal number to a lower decimal number

7

Using JavaScript how can I round a decimal number with several decimal places to a number with two decimal places with the lowest decimal number? Example:

44,97714285714286

To

44,97

I have already used the Math.floor but this rounds to the lowest integer, where the value is 44 and other ways that did not work and when dealing with monetary values need precision.

    
asked by anonymous 06.08.2015 / 15:38

4 answers

6

If you want to round down, simply add 2 decimal places ( * 100 ), make Math.floor and then divide by 100 again.

To round up you can use .toFixed() , that is (49.599).toFixed(2) gives 49.60 but I think that's not what you want.

So, a simpler version of how to shorten the decimal places below:

function arredondar(nr) {
    if (nr.indexOf(',') != -1) nr = nr.replace(',', '.');
    nr = parseFloat(nr) * 100;
    return Math.floor(nr) / 100;
}

jsFiddle: link

If you want a function that accepts the house number as an argument, you can do this:

function arredondar(str, casas) {
    if (str.indexOf(',') != -1) str = str.replace(',', '.');
    if (!casas) casas = 0;
    casas = Math.pow(10, casas);
    str = parseFloat(str) * casas;
    return Math.floor(str) / casas;
}

jsFiddle: link

    
06.08.2015 / 15:47
6

You can use .toFixed to define how many decimal places.

See an example:

var numObj = 12345.6789;

numObj.toFixed();       // Returns '12346'
numObj.toFixed(1);      // Returns '12345.7'
numObj.toFixed(6);      // Returns '12345.678900'
(1.23e+20).toFixed(2);  // Returns '123000000000000000000.00'
(1.23e-10).toFixed(2);  // Returns '0.00'
2.34.toFixed(1);        // Returns '2.3'
-2.34.toFixed(1);       // Returns -2.3
(-2.34).toFixed(1);     // Returns '-2.3'
    
06.08.2015 / 15:45
5

Do this:

document.body.innerHTML += Math.floor(44.97714285714286 * 100) / 100
    
06.08.2015 / 15:46
3

If you want x's after the comma, you can do this:

function arred(d,casas) { 
   var aux = Math.pow(10,casas)
   return Math.floor(d * aux)/aux
}

Then just call the function. Examples:

arred(44.97714285714286,0) //44
arred(44.97714285714286,1) //44.9
arred(44.97714285714286,2) //44.97
arred(44.97714285714286,3) //44.977
arred(44.97714285714286,4) //44.9771
    
06.08.2015 / 15:57