admin管理员组文章数量:1379578
this is the input
<input type="text" name="price" class="solo-numeros">
with this function
$(".solo-numeros").blur(function() {
var numb = parseFloat($(this).val().replace(/\D/g,"")).toFixed(2);
$(this).val(numb);
});
i try to change the result from the input to a float with two decimals
so i try
555.61
but on blur the value change to
55561.00
why is that????
this is the input
<input type="text" name="price" class="solo-numeros">
with this function
$(".solo-numeros").blur(function() {
var numb = parseFloat($(this).val().replace(/\D/g,"")).toFixed(2);
$(this).val(numb);
});
i try to change the result from the input to a float with two decimals
so i try
555.61
but on blur the value change to
55561.00
why is that????
Share Improve this question edited May 4, 2013 at 22:41 Sparky 98.8k26 gold badges202 silver badges290 bronze badges asked May 4, 2013 at 21:46 andrescabana86andrescabana86 1,7888 gold badges32 silver badges56 bronze badges 1- You are removing the decimal separator with .replace... – bfavaretto Commented May 4, 2013 at 21:49
5 Answers
Reset to default 1This happens because you're removing non-numeric characters (\D
), such as a period. So "55.61"
bees "5561"
, which is then made into a two-decimal string-representation of a float, hence "5561.00"
References:
- JavaScript regular expressions.
String.replace()
.Number.toFixed()
.
$(this).val().replace(/\D/g,"")
this part replaces the decimal point .
in your number, 555.61
, making it an integer with value 55561
, then toFixed()
makes it 55561.00
. Workaround could be to use
$(this).val().replace(/[^0-9\.]/g,"")
Try replacing the line where you pute numb with this one:
var numb = _toPrecision( parseFloat( $(this).val() ) , 2 );
Using this function:
var _toPrecision = function( number , precision ){
var prec = Math.pow( 10 , precision );
return Math.round( number * prec ) / prec;
}
\D
replaces any non digit character. .
is not a digit character, hence it's being removed. Use [^\d\.]
instead, which means "any character that is not a digit, and not the character .
.
var numb = parseFloat($(this).val().replace(/[^\d\.]/g, "")).toFixed(2);
$(this).val(numb);
Output:
parseFloat(String('123.456').replace(/[^\d\.]/g, "")).toFixed(2);
//123.46
You replace all non-digits in the string which will give you "55561" from "555.61" (the period gets replaced by your regex replace call). This in turn is evaluated to 55561.00 by the toFixed() method.
Try parsing an optional period in your regex something like (untested)
var numb=parseFloat($(this).val().replace(/\D(\.\D+)?/g,"")).toFixed(2);
本文标签: javascriptparse float with two decimals Stack Overflow
版权声明:本文标题:javascript - parse float with two decimals, - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744251998a2597294.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论