gpt4 book ai didi

Javascript 将变量视为字符串,为什么?

转载 作者:行者123 更新时间:2023-11-30 06:59:45 24 4
gpt4 key购买 nike

我有变量 y,它是一个小计。它的值根据 html 发生的情况而不同,但在整个脚本中我这样声明它:

var y = 21.78;

等为什么在我加总的最后一个等式中,当我想添加值时它会将它们视为字符串?

var tax = (0.055*y).toFixed(2);
var totalprice = y+tax;
/* totalprice holds "21.781.20" instead of 22.98 */

最佳答案

根据:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed

toFixed() 返回:

A string representation of number that does not use exponential notation and has exactly digits digits after the decimal place.

因此,y+tax 被转换为字符串,因为其中一个操作数是字符串。

在我看来,这是有道理的,因为 Javascript 的固有数字类型无法存储特定数量的小数位数字,因此字符串将是最合适的数据结构来存储它。

我建议您在 调用 toFixed() 之前完成所有添加,因为该方法最适合格式化显示输出。

var taxRate = 0.055;
var subtotal = 21.78;

var tax = (taxRate * subtotal).toFixed(2),
totalprice = ((1+taxRate) * subtotal).toFixed(2);
document.write(totalprice);

关于Javascript 将变量视为字符串,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10080030/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com