Javascript 添加两个小数位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8083018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Adding Two Decimal Places
提问by Aaron Coronado
This is my Code so far. I want to know how to return the answer with two decimal places. EX. Instead of 515.3 I want 515.30 or instead of 500 I want it to return 500.00.
到目前为止,这是我的代码。我想知道如何返回两位小数的答案。前任。我想要 515.30 而不是 515.3 或者我想要它返回 500.00 而不是 500。
<HTML>
<HEAD>
<TITLE>Simple Adder</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function CalculateSum(Atext, form)
{
var A = parseFloat(Atext);
form.Answer.value = A * .03+.30+A;
}
function ClearForm(form)
{
form.input_A.value = "";
form.Answer.value = "";
}
// end of JavaScript functions -->
</SCRIPT>
</HEAD>
<BODY>
<P><FONT SIZE="+2">Credit Card Payment Calculator</FONT></P>
<FORM NAME="Calculator" METHOD="post">
<P>Enter Base Rent: <INPUT TYPE=TEXT NAME="input_A" SIZE=10></P>
<P><INPUT TYPE="button" VALUE="Calculate Rent & Fees Payment" name="AddButton" onClick="CalculateSum(this.form.input_A.value, this.form)"></P>
<P><INPUT TYPE="button" VALUE="Clear Fields" name="ClearButton" onClick="ClearForm(this.form)"></P>
<P>Final Amount = <INPUT TYPE=TEXT NAME="Answer" SIZE=12></P>
</FORM>
</BODY>
</HTML>
回答by Alex Turpin
Use Number.prototype.toFixed
. For example:
使用Number.prototype.toFixed
. 例如:
var a = 515.3;
alert(a.toFixed(2));
Note that this converts the number to a string so only use it to display to the user.
请注意,这会将数字转换为字符串,因此仅将其用于向用户显示。