我知道这个问题以前有人问过,但我试图解决的问题有几个。
function calc(number) {
var num = number;
var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0];
return with2Decimals
},这是我发现的另一个工作方式,与我更喜欢的方式一样:
function decimalFix(numToBeTruncated, numOfDecimals) {
var theNumber = numToBeTruncated.toString();
var pointIndex = theNumber.indexOf('.');
return +(theNumber.slice(0, pointIndex > -1 ? ++numOfDecimals + pointIndex : undefined));
}这一问题:
在大多数情况下,除了非常大的十进制数外,它们工作得很好。例如,在javascript中,数字0.00000001990202020291读取为0.00000001990202020291,因此,如果我想要其中的9位小数位,不要给我0.000000019,而是给出1.99020202,这是非常离谱的。
为什么?
很多人对我/其他人想要解决这个问题感到非常不安,因为这在他们看来是不正统的。它主要是与货币有关,而不是失去分数的价值,如果我只允许在我的计算如此精确。例如,有时我需要计算小数点6-8位以下的微事务,但是如果我选择四舍五入的话,我会在这个过程中失去或获得金钱。
我很感谢有人能在这个问题上提供任何帮助或指导。
预期成果:
decimalFix(0.0000000199020202029,9) // 0.000000019发布于 2018-01-06 18:55:00
你已经说过你需要小数点右边的6-8位,左边的6-8位(但通常更像1-3位)。
这就是JavaScript的数字类型(IEEE-754双精度二进制浮点)的边缘(如果真的是8.8,越过边缘)所能做到的。不管十进制在哪里,JavaScript的浮点在丢失信息之前大约有15位小数点的精度。(这根本不是故事的全部。)
好消息: JavaScript获得了可用于此的BigInt类型(通过将值乘以100,000,000,因此它们是整数),details 这里。在此之前,您可能会考虑使用现有的“大数字”库之一。
如果您需要使用JavaScript的数字,我将使用整数。使用整数,您的精确范围是-Number.MAX_SAFE_INTEGER - 1通过Number.MAX_SAFE_INTEGER + 1.从9,007,199,254,740,992到9,007,199,254,740,992。这样,您就可以得到--小数点的左边和右边的7个数字(当然,也可以得到8个左、7个右)。所以,如果我们使用的是小数点右八位,左边七位(很好的限度内),那就是-9,999,999.99999999通过9,999,999.99999999。
计算将使用Math.trunc删除小数部分(假设您希望截断到零)。没有科学符号的输出是微不足道的:
str = String(number);
str = str.substring(0, str.length - 8) + "." + str.substr(-8);示例:
function toString(number) {
var str = String(number);
str = str.substring(0, str.length - 8) + "." + str.substr(-8);
return str;
}
console.log(toString(999999999999999));
console.log(toString(123456712345678));
console.log(toString(765432187654321));
发布于 2018-01-06 19:41:53
它主要是与货币有关,而不是失去分数的价值,如果我只允许在我的计算如此精确。例如,有时我需要计算小数点6-8位以下的微事务,但是如果我选择四舍五入的话,我会在这个过程中失去或获得金钱。
//rounding to an arbitrary precision
function round(value, precision = 1) {
return Math.round(value / precision) * precision
}
console.log("round");
console.log(round(1.23456789, 0.001));
console.log(round(1.23456789, 1 / 4));
console.log(round(Date.now(), 1000*60*60)); //the current timestamp rounded to the hour
//rounding to a certain amount of decimal places
function roundToDecimalPlaces(value, decimalPlaces = 0) {
return round(value, "1e" + (-decimalPlaces));
}
console.log("roundToDecimalPlaces");
console.log(roundToDecimalPlaces(1.23456789, 4));
console.log(roundToDecimalPlaces(0.0000000199020202029, 9));
//and truncating everything after a certain amount of decimal places
function decimalFix(value, decimalPlaces = 0) {
let precision = "1e" + (-decimalPlaces);
return Math[value < 0 ? "ceil" : "floor"](value / precision) * precision;
}
console.log("decimalFix");
console.log(decimalFix(0.0000000199020202029, 9));.as-console-wrapper {
top: 0;
max-height: 100%!important
}
但你为什么一开始就想限制精度?如果它包含视图,以及如何显示值,那么这是错误的方法。
那么您应该查看Number#toFixed、Number#toPrecision和Number#toLocaleString。
https://stackoverflow.com/questions/48130516
复制相似问题