Javascript Adding Two Decimal Places

℡╲_俬逩灬. 提交于 2019-12-08 21:01:18

问题


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.

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

回答1:


Use Number.prototype.toFixed. For example:

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.



来源:https://stackoverflow.com/questions/8083018/javascript-adding-two-decimal-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!