如何使用javascript删除浮点数小数点后的零[重复]

时间:2021-02-08 17:08:35

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

可能重复:jQuery:逗号后将数字四舍五入为2位数

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.

在JavaScript中打印一个数字时,我只希望在小数点后只保留三位数。我使用的代码显示小数点后的8位以上。任何人都可以指导我如何使用JavaScript删除剩余的数字。

This is my JavaScript code:

这是我的JavaScript代码:

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

4.050000000000001

I want:

我想要:

4.050

4.050

Any help would be appreciated, thank you.

任何帮助将不胜感激,谢谢。

5 个解决方案

#1


1  

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

请试试这个数量= amount.toFixed(3);

#2


1  

use toFixed() method of javascript

使用javascript的toFixed()方法

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

toFixed()方法将数字转换为字符串,保持指定的小数位数。

var amount= amount.toFixed(3);  //3 digits after decimal

#3


0  

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:

我不建议使用.toFixed()来舍入数字,因为它返回一个字符串。在你的情况下,这可能是相当不错的,因为它看起来像是用于显示,但一般来说,做一些数学:

function betterToFixed(num, decPlaces) {
  var factor = Math.pow(10, decPlaces);
  return Math.round(num * factor) / factor;
}

#4


0  

Use toFixed():

使用toFixed():

amount = amount.toFixed(3);

#5


0  

amount= amount.toFixed(3);

this will give you the solution you want

这将为您提供所需的解决方案

#1


1  

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

请试试这个数量= amount.toFixed(3);

#2


1  

use toFixed() method of javascript

使用javascript的toFixed()方法

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

toFixed()方法将数字转换为字符串,保持指定的小数位数。

var amount= amount.toFixed(3);  //3 digits after decimal

#3


0  

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:

我不建议使用.toFixed()来舍入数字,因为它返回一个字符串。在你的情况下,这可能是相当不错的,因为它看起来像是用于显示,但一般来说,做一些数学:

function betterToFixed(num, decPlaces) {
  var factor = Math.pow(10, decPlaces);
  return Math.round(num * factor) / factor;
}

#4


0  

Use toFixed():

使用toFixed():

amount = amount.toFixed(3);

#5


0  

amount= amount.toFixed(3);

this will give you the solution you want

这将为您提供所需的解决方案