最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - parse float with two decimals, - Stack Overflow

programmeradmin9浏览0评论

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
Add a ment  | 

5 Answers 5

Reset to default 1

This 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);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论