admin管理员组文章数量:1356756
I have a variable i=28.57142857142857; I want to alert(i); alert this variable on user screen. But I want only two digits after decimal. i.e 28.57
How to do it.
I have a variable i=28.57142857142857; I want to alert(i); alert this variable on user screen. But I want only two digits after decimal. i.e 28.57
How to do it.
Share Improve this question asked Jun 4, 2010 at 8:57 Vaibhav JainVaibhav Jain 34.5k49 gold badges115 silver badges166 bronze badges3 Answers
Reset to default 5try using toFixed:
alert(i.toFixed(2));
If you need the precision mentioned in the next answer from Jappie, you could overwrite the native toFixed method like this:
Number.prototype.toFixed = function (precision) {
var power = Math.pow(10, precision || 0);
return String(Math.round(this * power) / power);
};
How about
alert(Math.round(i * 100) / 100);
There are problems with toFixed. See this post.
100% working!!!!
<html>
<head>
<script>
function replacePonto(){
var input = document.getElementById('qtd');
var ponto = input.value.split('.').length;
var slash = input.value.split('-').length;
if (ponto > 2)
input.value=input.value.substr(0,(input.value.length)-1);
if(slash > 2)
input.value=input.value.substr(0,(input.value.length)-1);
input.value=input.value.replace(/[^0-9.-]/,'');
if (ponto ==2)
input.value=input.value.substr(0,(input.value.indexOf('.')+3));
if(input.value == '.')
input.value = "";
}
</script>
</head>
<body>
<input type="text" id="qtd" maxlength="10" style="width:140px" onkeyup="return replacePonto()">
</body>
</html>
本文标签: netAllow only two digits after decimal in javascriptStack Overflow
版权声明:本文标题:.net - Allow only two digits after decimal in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744058215a2583643.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论