在使用toString函数后,我在电子商务网页的购物车代码中获得了total_amount,但是当我将14.82字符串转换为int数时,小数就会消失.
<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>
Run Code Online (Sandbox Code Playgroud)
怎么了?
T.J*_*der 23
如果输入字符串是"14,82"并且您想要该值14.82,则需要将其转换,为a .然后使用parseFloat:
var total_amount_int = parseFloat(
total_amount_string.replace(/,/g, ".")
).toFixed(2);
Run Code Online (Sandbox Code Playgroud)
parseInt将只解析定义整数的字符串的前导部分("int"="integer"="整数"),因此它停在,.parseFloat将解析一个十进制数,但只能理解.为小数点,,即使在,小数点的区域中也是如此.