javascript - parseFloat & toFixed 只返回 1 个小数点
问题描述
在下面工作时,在记录数组“提示”时,推入其中的数字似乎只有一位小数。
在添加 parseFloat 之前,它会返回 2 个小数点,但它是作为字符串返回的。添加 parseFloat 后,它现在似乎只返回一个小数点。
谢谢你。
var tips = [];
var calculateTip = function(bill) {
switch (true) {
case bill < 50:
tips.push(parseFloat((bill * 0.2).toFixed(2)));
break;
case bill >= 50 && bill < 201:
tips.push(parseFloat((bill * 0.15).toFixed(2)));
break;
default:
tips.push(parseFloat((bill * 0.10).toFixed(2)));
}
}
calculateTip(124);
calculateTip(48);
calculateTip(268);
console.log(tips);
解决方案
Number.prototype.toFixed()
返回一个你用正确的小数位数调用它的表示,但是如果你用它解析它string
,那些会消失,因为不关心尾随零。number
number
parseFloat
number
您可以通过摆脱以下内容来解决此问题parseFloat
:
const tips = [];
function calculateTip(bill) {
if (bill < 50)
tips.push((bill * 0.2).toFixed(2));
else if (bill >= 50 && bill < 201)
tips.push((bill * 0.15).toFixed(2));
else
tips.push((bill * 0.10).toFixed(2));
}
calculateTip(124);
calculateTip(48);
calculateTip(268);
console.log(tips);
推荐阅读
- erlang - 如何将消息发送到多个进程
- c# - 使用命名空间序列化 XML
- javascript - 当我想通过 json 获取图像 src 并通过车把将其添加到轮播时,猫头鹰轮播有问题?
- parsing - 解析从 Python 发送的 javascript 中的字符串列表
- haproxy - 重新加载 HAProxy 配置时如何保持会话值?
- colors - 如何将材质调色板转换为 Flutter 主题?
- mount - nfs mount导致服务器卡死
- sonarqube - 无法在 Sonarqube 中打开网页
- javascript - 加载 iframe 时网页滚动卡住
- html - 如何在移动端设置两行,在桌面设置单行?