Reputation: 1788
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????
Upvotes: 1
Views: 12609
Reputation: 66
Try replacing the line where you compute 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;
}
Upvotes: 1
Reputation: 513
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);
Upvotes: 0
Reputation: 39522
\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
Upvotes: 0
Reputation: 8872
$(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,"")
Upvotes: 1
Reputation: 253308
This happens because you're removing non-numeric characters (\D
), such as a period. So "55.61"
becomes "5561"
, which is then made into a two-decimal string-representation of a float, hence "5561.00"
References:
Upvotes: 1