Rounding a decimal to a lower decimal

Asked

Viewed 13,678 times

9

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

44,97714285714286

To

44,97

I’ve used the Math.floor but this round off to the lowest integer where the value 44 and other ways that have not worked and when it comes to monetary values need to have precision.

  • 1

    A reference here at Sopt on how to handle money in Javascript: http://answall.com/q/11018/129

4 answers

8


If you want to round the bottom just add 2 decimal places (* 100), do Math.floor and then split by 100 again.

To round up you can use the .toFixed(), that is to say (49.599).toFixed(2) gives 49.60 but I don’t think that’s what you want.

Thus, 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: http://jsfiddle.net/voxnmfm2/

If you want a function that accepts as argument the home number you can do so:

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: http://jsfiddle.net/voxnmfm2/1/

7

You can use the .toFixed to define how many decimal places you want.

Take 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'

6

3

If you want x houses after the comma, you can do so:

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

Then simply 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.