javascript 用两位小数解析浮点数,

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16379290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:24:42  来源:igfitidea点击:

parse float with two decimals,

javascriptjquery

提问by andrescabana86

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????

这是为什么????

回答by David says reinstate Monica

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"

发生这种情况是因为您要删除非数字字符 ( \D),例如句点。所以"55.61"变成"5561",然后将其制成浮点数的两位十进制字符串表示形式,因此"5561.00"

References:

参考:

回答by Ejaz

$(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(/\D/g,"")这部分替换.您的数字中的小数点555.61,使其成为具有 value 的整数55561,然后toFixed()使其成为55561.00。解决方法可能是使用

$(this).val().replace(/[^0-9\.]/g,"") 

回答by d3mi3n

Try replacing the line where you compute numb with this one:

尝试用这个替换计算 numb 的行:

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;
}

回答by h2ooooooo

\Dreplaces 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 ..

\D替换任何非数字字符。.不是数字字符,因此它被删除。使用[^\d\.]替代,意思是“这不是一个数字,而不是任何字符.

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

回答by hannenz

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.

您替换字符串中的所有非数字,这将为您提供“555.61”中的“55561”(句点被您的正则表达式替换调用替换)。这反过来又通过 toFixed() 方法评估为 55561.00。

Try parsing an optional period in your regex something like (untested)

尝试解析正则表达式中的可选句点,例如(未经测试)

 var numb=parseFloat($(this).val().replace(/\D(\.\D+)?/g,"")).toFixed(2);