在 Javascript 中设置 parseFloat 值的最大值

问题描述 投票:0回答:1

我使用以下命令来解析 div 中的数字(该数字是由 php 通过从数据库获取来创建的)

var price = parseFloat($('#priceofproduct').text().replace(',', '.'));

现在,大多数时候它的结果是 5.99 欧元。但有时它也会导致 5,9900000009 欧元,因为这是它以某种方式插入数据库的方式。如何设置最多只显示 4 位数字的限制(例如 €39,99)?

javascript
1个回答
0
投票

就像一些评论所说,浮点数/双精度数对于精确计算来说非常棘手,特别是对于 JavaScript,所以我不建议在财务计算中使用这种方法。 话虽这么说,“四位数字”有多种解释: 如果您的问题只是关于如何四舍五入到小数点后两位,则可以使用大约

本文

中描述的方法来完成以下操作:

function compactify(f) { return Math.round(f * 100) / 100; } console.log(compactify(5.9900000009)); console.log(compactify(2.000000001));


如果您想最多显示四位小数,并根据小数点
之前

的数字删除末尾的精度,您可以执行以下操作:

function compactify(f) { var log = Math.floor((Math.log(Math.floor(f)) / Math.log(10))) + 1; // Determine the number of place values if (log < 2) { return Math.round(f * 100) / 100; } else if (log == 3) { return Math.round(f * 10) / 10; } else if (log == 4) { // We use the floor function here since you usually would want to only see the non-decimal digits on their own rather than a rounded number return Math.floor(f); } } console.log("5.43: " + compactify(5.43)); console.log("3.2434: " + compactify(3.2434)); console.log("200.212: " + compactify(200.212)); console.log("5234.81: " + compactify(5234.81));


然而,后一种方法对于显示价格来说相当具有误导性,它仅适用于 1000 EU 以下的价格,因为在不删除重要数字的情况下无法将其截断。

© www.soinside.com 2019 - 2024. All rights reserved.