3

Possible Duplicate:
jQuery: rounding numbers to 2 digits after comma

While printing out a number in JavaScript, I only want keep only three digits after the decimal point. The code I am using shows more than 8 digits after the decimal point. Could anyone guide me on how to remove the remaining digits using JavaScript.

This is my JavaScript code:

function  doMath() { 

   var nvalue; var amount;
   var price= 0.27;
   nvalue = document.getElementById("message").value;

   amount=(nvalue*price);

   document.getElementById("total").value=amount ;

}

Output:

4.050000000000001

I want:

4.050

Any help would be appreciated, thank you.

Community
  • 1
  • 1
user1790858
  • 33
  • 1
  • 5

5 Answers5

1

use toFixed() method of javascript

toFixed() method converts a number into a string, keeping a specified number of decimals.

var amount= amount.toFixed(3);  //3 digits after decimal
bipen
  • 36,319
  • 9
  • 49
  • 62
1

I would not recommend using .toFixed() for rounding numbers, since it returns a string. In your case, this is probably quite ok, since it looks like it's for display, but in general, do some maths:

function betterToFixed(num, decPlaces) {
  var factor = Math.pow(10, decPlaces);
  return Math.round(num * factor) / factor;
}
nickf
  • 537,072
  • 198
  • 649
  • 721
0

Use toFixed():

amount = amount.toFixed(3);
Johannes Mittendorfer
  • 1,102
  • 10
  • 17
0

Please try this
amount=amount.toFixed(3);

Elby
  • 1,624
  • 3
  • 23
  • 42
0
amount= amount.toFixed(3);

this will give you the solution you want

PRATIK
  • 27
  • 3