For example:
12345
Format Is 12,345.00
12345.6
Format Is 12,345.60
12345.67
Format Is 12,345.67
Leave only two decimal places.
After I came back, I wroteFormatFunction. The number of decimal places can be controlled and automatically rounded.
CodeReference Function fmoney (S, N)
{
N = n> 0 & n <= 20? N: 2;
S = parsefloat (S + ""). Replace (/[^ \ D \.-]/g, ""). tofixed (n) + "";
VaR L = S. Split (".") [0]. Split (""). Reverse (),
R = S. Split (".") [1];
T = "";
For (I = 0; I <L. length; I ++)
{
T + = L [I] + (I + 1) % 3 = 0 & (I + 1 )! = L. length? ",":"");
}
Return T. Split (""). Reverse (). Join ("") + "." + R;
}
Call: fmoney ("12345.675910", 3), return 12,345.676
Restore function: Reference Function rmoney (s)
{
Return parsefloat (S. Replace (/[^ \ D \.-]/g ,""));
}
Example (Save the Code as an HTML file and run it to view the effect): Reference <SCRIPT>
Function fmoney (S, N)
{
N = n> 0 & n <= 20? N: 2;
S = parsefloat (S + ""). Replace (/[^ \ D \.-]/g, ""). tofixed (n) + "";
VaR L = S. Split (".") [0]. Split (""). Reverse (),
R = S. Split (".") [1];
T = "";
For (I = 0; I <L. length; I ++)
{
T + = L [I] + (I + 1) % 3 = 0 & (I + 1 )! = L. length? ",":"");
}
Return T. Split (""). Reverse (). Join ("") + "." + R;
}
Function rmoney (s)
{
Return parsefloat (S. Replace (/[^ \ D \.-]/g ,""));
}
Function g (ID)
{
Return document. getelementbyid (ID );
}
Window. onload = function ()
{
VaR num,
TXT = g ("TXT "),
Txt2 = g ("txt2 "),
BTN = g ("BTN "),
Btn2 = g ("btn2 "),
SPAN = g ("span ");
BTN. onclick = function ()
{
Num = parseint (G ("num"). value );
TXT. value = fmoney (txt. Value, num );
Txt2.value = fmoney (txt2.value, num );
}
;
Btn2.onclick = function ()
{
Num = parseint (G ("num"). value );
Span. innerhtml = "=" + fmoney (rmoney (txt. Value) + rmoney (txt2.value), num );
}
;
}
;
</SCRIPT>
Number of decimal places:
<Select id = "num">
<Option value = "2"> 2 </option>
<Option value = "3"> 3 </option>
<Option value = "4"> 4 </option>
<Option value = "5"> 5 </option>
</SELECT>
<Input type = "text" id = "TXT" value = "12345.675910"> +
<Input type = "text" id = "txt2" value = "1223"> <span id = "span"> </span>
<Br>
<Input type = "button" id = "BTN" value =" Format ">
<Input type = "button" id = "btn2" value = "add">