javascript - 如何在javascript中获取数字的浮动值?
问题描述
我正在尝试在不四舍五入的情况下将数字精确到小数点后
我能找到的最接近的是来自这个来源
num = num.toString(); //If it's not already a String
num = num.slice(0, (num.indexOf("."))+3); //With 3 exposing the hundredths place
Number(num); //If you need it back as a Number
但它有它的局限性
这就是我想要实现的目标:
if n=3
16 -> 16.000
16.000001 -> 16.000
16.12345 -> 16.123
4239.20902190 -> 4239.209
我试图远离数学方法,而是使用字符串方法,因为数学方法有时会变得不可预测,那么有什么现代方法可以达到预期的结果吗?
我可能给问题加上了不正确的标题,所以欢迎任何编辑
解决方案
如果你将一个数字乘以 10,然后用它Math.floor
来删除小数点后的所有内容,然后除以 10,你得到原始数字的值到小数点后一位,没有四舍五入。如果您使用 100 而不是 10,则它将是 2 个小数位。1000 等于 3、10000-4 等。
然后使用number.prototype.ToFixed(n)
,我们可以得到一个总是有n
小数位的字符串。
将这些组合在一起,您会得到类似的东西:
function toDecimalPlaceWithoutRounding(number, precision) {
const factor = 10 ** precision; // "x ** y" means x to the power of y
const value = Math.floor(number * factor) / factor;
return value.toFixed(precision);
}
对此的快速测试:
function toDecimalPlaceWithoutRounding(number, precision) {
const factor = 10 ** precision;
const value = Math.floor(number * factor) / factor;
return value.toFixed(precision);
}
for (let i = 0; i < 10; i++) {
const number = Math.random() * 20;
const result = toDecimalPlaceWithoutRounding(number, 3);
console.log(number,result);
}
注意你可以只使用.toFixed
,但它会四舍五入。例如。(3.555).toFixed(2)
会给"3.56"
。
编辑负面支持:
function toDecimalPlaceWithoutRounding(number, precision) {
const factor = 10 ** precision;
const roundFunc = number > 0 ? Math.floor : Math.ceil; // use floor for positive numbers, ceil for negative
const value = roundFunc(number * factor) / factor;
return value.toFixed(precision);
}
for (let i = 0; i < 10; i++) {
const number = Math.random() * 20 - 10;
const result = toDecimalPlaceWithoutRounding(number, 3);
console.log(number,result);
}
推荐阅读
- python - Python-Docker 容器无法连接到 MariaDB-Docker 容器
- python - 除了多维数组中的 int
- mysql - 在 MariaDB 中完全连接 2 个表
- python - django-admin startapp v/s python manage.py startapp
- javascript - 用于预购遍历检查的 Javascript 等效代码
- html - 为什么图像边框设置为内联块
- r - 如何计算保存在多列表中的数据的唯一出现次数?
- autodesk-forge - 如何导出多个 3D 视图
- .net - 实体框架数据库优先方法 Pascal 案例
- mysql - 我在带有下划线的 sql 存储过程中遇到语法错误