javascript 如何在Javascript中的小数点后附加一个额外的“零”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8034429/
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
How to append an extra 'Zero' after decimal in Javascript
提问by Somi Meer
Hye, Iam new to javascript working with one textbox validation for decimal numbers . Example format should be 66,00 .but if user type 66,0 and dont type two zero after comma then after leaving text box it should automatically append to it .so that it would be correct format of it . How can i get this .How can i append ?? here is my code snippet.
嘿,我是 javascript 新手,使用一个文本框验证十进制数字。示例格式应该是 66,00 。但是如果用户输入 66,0 并且不在逗号后输入两个零,那么在离开文本框后它应该自动附加到它。以便它是正确的格式。我怎样才能得到这个。我怎样才能追加?这是我的代码片段。
function check2(sender){
var error = false;
var regex = '^[0-9][0-9],[0-9][0-9]$';
var v = $(sender).val();
var index = v.indexOf(',');
var characterToTest = v.charAt(index + 1);
var nextCharAfterComma = v.charAt(index + 2);
if (characterToTest == '0') {
//here need to add
}
}
回答by OptimusCrime
Use .toFixed(2)
利用 .toFixed(2)
Read this article: http://www.javascriptkit.com/javatutors/formatnumber.shtml
阅读这篇文章:http: //www.javascriptkit.com/javatutors/formatnumber.shtml
|EDIT| This will also fix the issue if a user types in too many decimals. Better to do it this way, rather than having a if to check each digit after the comma.
|编辑| 如果用户输入太多小数,这也将解决该问题。最好这样做,而不是用 if 来检查逗号后的每个数字。