我在Javascript中有一个文本框。当我在文本框中输入'0000.00'
时,我想知道如何将其转换为只有一个前导零,例如'0.00'
。
答案 0 :(得分:48)
更简化的解决方案如下。看看这个!
var resultString = document.getElementById("theTextBoxInQuestion")
.value
.replace(/^[0]+/g,"");
答案 1 :(得分:28)
str.replace(/^0+(?!\.|$)/, '')
'0000.00' --> '0.00'
'0.00' --> '0.00'
'00123.0' --> '123.0'
'0' --> '0'
答案 2 :(得分:13)
var value= document.getElementById("theTextBoxInQuestion").value;
var number= parseFloat(value).toFixed(2);
答案 3 :(得分:9)
听起来你只想删除前导零,除非只剩下一个(整数为“0”或浮点数为“0.xxx”,其中x可以是任何东西)。
这应该适合第一次切割:
while (s.charAt(0) == '0') { # Assume we remove all leading zeros
if (s.length == 1) { break }; # But not final one.
if (s.charAt(1) == '.') { break }; # Nor one followed by '.'
s = s.substr(1, s.length-1)
}
答案 4 :(得分:5)
您可以使用此代码:
<script language="JavaScript" type="text/javascript">
<!--
function trimNumber(s) {
while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
return s;
}
var s1 = '00123';
var s2 = '000assa';
var s3 = 'assa34300';
var s4 = 'ssa';
var s5 = '121212000';
alert(s1 + '=' + trimNumber(s1));
alert(s2 + '=' + trimNumber(s2));
alert(s3 + '=' + trimNumber(s3));
alert(s4 + '=' + trimNumber(s4));
alert(s5 + '=' + trimNumber(s5));
// end hiding contents -->
</script>
答案 5 :(得分:5)
好的简单解决方案。唯一的问题是当字符串是&#34; 0000.00&#34;结果是普通的0.但除此之外,我认为这是一个很酷的解决方案。
var i = "0000.12";
var integer = i*1; //here's is the trick...
console.log(i); //0000.12
console.log(integer);//0.12
对于某些情况,我认为这可行...
答案 6 :(得分:2)
试试这个:
<input type="text" onblur="this.value=this.value.replace(/^0+(?=\d\.)/, '')">
答案 7 :(得分:0)
您可以使用正则表达式将单个前导零替换为一个:
valueString.replace(/^(-)?0+(0\.|\d)/, '$1$2')
>'-000.0050'.replace(/^(-)?0+(0\.|\d)/, '$1$2')
< "-0.0050"
>'-0010050'.replace(/^(-)?0+(0\.|\d)/, '$1$2')
< "-10050"
匹配项:<beginning of text><optional minus sign><any sequence of zeroes><either a zero before the dot or another digit>
替换为:<same sign if available><the part of the string after the sequence of zeroes>
^是文本的开头
?表示可选(指前一个字符)
(a | b)表示a或b
。是点(转义为表示特殊含义)
\ d是任意数字
$ 1表示您在第一组()中找到的内容
$ 2表示您在第二组()中找到的内容