JavaScript的问题" parseInt()"十进制字符串 [英] Problems with JavaScript "parseInt()" decimal string
问题描述
在使用toString函数后,我在电子商务网页的购物车代码中获得了total_amount,但是当我将14.82字符串转换为int数时,小数就会消失。
I get the total_amount in cart code of ecommerce web page, after I use toString function, but when I convert the 14.82 string to int number, the decimals disappear.
<script>
var total_amount_string = <?=json_encode($cart['total_pvp'])?>;//-> 14,82
var total_amount_int = parseInt(total_amount_string).toFixed(2); //-> 14.00(here is the error)
console.log(total_amount_string) //-> 14,82
console.log(total_amount_int) //-> 14.00
</script>
什么事?
推荐答案
如果输入字符串是14,82
,并且您希望值 14.82
,你需要将,
转换为。
,然后使用 parseFloat
:
If the input string is "14,82"
and you want the value 14.82
, you'll need to convert the ,
to a .
and then use parseFloat
:
var total_amount_int = parseFloat(
total_amount_string.replace(/,/g, ".")
).toFixed(2);
parseInt
只解析领先部分定义整数的字符串(int=integer=整数),因此它停在,
。 parseFloat
将解析一个十进制数字,但只能理解。
作为小数点,而不是,
,即使在的区域内,
也是小数点。
parseInt
will only parse the leading part of the string that defines a whole number ("int" = "integer" = "whole number"), so it stops at the ,
. parseFloat
will parse a decimal number, but only understands .
as the decimal point, not ,
, even in locales where ,
is the decimal point.
这篇关于JavaScript的问题" parseInt()"十进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!