0

I need a round to two number after comma. example

5000.0000 to 5000

5000.123 to 5000.12

5000.136 to 5000.13

how do this?

I need function x.toFixed(2); but if at the end of two zero, then they should not show

Mediator
  • 14,951
  • 35
  • 113
  • 191
  • I think you want to round after "dot" you specified after comma" – Miqdad Ali Jun 05 '12 at 09:30
  • 1
    @MiqdadAli: Not all countries use a decimal dot. For example, in Germany we use `123.456.789,12345` (actually, the official way is `123 456 789,12345` but most people use dots anyway - but the decimal point is always the comma) – ThiefMaster Jun 05 '12 at 09:31
  • Possible Duplicate: **[JavaScript: formatting number with exactly two decimals](http://stackoverflow.com/questions/1726630/javascript-formatting-number-with-exactly-two-decimals)** – Siva Charan Jun 05 '12 at 09:33
  • @ThiefMaster, true enough, but he did use periods/dots in his question. – David Thomas Jun 05 '12 at 09:34
  • @freakish you should seriously put that as an answer :s – Andreas Wong Jun 05 '12 at 09:45
  • @SiGanteng I could, but then again OP should google for it in the first place. It is common knowledge after all. – freakish Jun 05 '12 at 09:57

4 Answers4

0

You can use this javascript function to round the number

function roundNumber(rnum, rlength) { 
  var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
return parseFloat(newnumber);
}

var num = roundNumber(5000.0000,0);   //will return 5000
Miqdad Ali
  • 6,129
  • 7
  • 31
  • 50
0

As @freakish suggests, toFixed is good idea to round numbers. If you want to floor it, I suggest

parseInt(5000.136*100)/100;
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
0

Since x.toFixed(2) returns a string you may do something like this:

function cut(str) {
    if (str[str.length-1] == "0")
        return str.substr(0, str.length-1);
    if (str[str.length-1] == ".")
        return str.substr(0, str.length-1);
    return str;
}

x = cut(cut(cut(x.toFixed(2))));

Not the most elegant (for example you could add the function to string's prototype), but definetly working.

freakish
  • 54,167
  • 9
  • 132
  • 169
-1

This link can help you

http://www.w3schools.com/jsref/jsref_tofixed.asp

Example

Convert a number into a string, keeping only two decimals:

var num = 5.56789; var n=num.toFixed(2);

The result of n will be:

5.57

Sahal
  • 4,046
  • 15
  • 42
  • 68