简体   繁体   English

如何在Javascript中的小数点后附加一个额外的“零”

[英]How to append an extra 'Zero' after decimal in Javascript

Hye, Iam new to javascript working with one textbox validation for decimal numbers .嘿,我是 javascript 新手,使用一个文本框验证十进制数字。 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 .示例格式应该是 66,00。但是如果用户输入 66,0 并且不在逗号后输入两个零,那么在离开文本框后它应该自动附加到它。这样它就会是正确的格式。 How can i get this .How can i append ??我怎样才能得到这个。我怎样才能追加? here is my code snippet.这是我的代码片段。

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

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 来检查逗号后的每个数字。

.toFixed() converts a number to string and if you try to convert it to a float like 10.00 then it is impossible. .toFixed() 将数字转换为字符串,如果您尝试将其转换为像 10.00 这样的浮点数,那么这是不可能的。

Example-例子-

  1. 10.toFixed(2) // "10.00" string 10.toFixed(2) // "10.00" 字符串
  2. parseFloat("10.00") // 10 parseFloat("10.00") // 10
  3. Number("10.00") // 10 Number("10.00") // 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM