假设我有一个值15.7784514,我想把它显示为15.77,没有舍入。
var num = parseFloat(15.7784514);
document.write(num.toFixed(1)+"<br />");
document.write(num.toFixed(2)+"<br />");
document.write(num.toFixed(3)+"<br />");
document.write(num.toFixed(10));
结果:
15.8
15.78
15.778
15.7784514000
如何显示15.77?
这并不是一个安全的替代方法,因为许多其他的例子都将数字转换为指数符号,这个函数没有覆盖这个场景
// typescript
// function formatLimitDecimals(value: number, decimals: number): number {
function formatLimitDecimals(value, decimals) {
const stringValue = value.toString();
if(stringValue.includes('e')) {
// TODO: remove exponential notation
throw 'invald number';
} else {
const [integerPart, decimalPart] = stringValue.split('.');
if(decimalPart) {
return +[integerPart, decimalPart.slice(0, decimals)].join('.')
} else {
return integerPart;
}
}
}
console.log(formatLimitDecimals(4.156, 2)); // 4.15
console.log(formatLimitDecimals(4.156, 8)); // 4.156
console.log(formatLimitDecimals(4.156, 0)); // 4
console.log(formatLimitDecimals(0, 4)); // 0
// not covered
console.log(formatLimitDecimals(0.000000199, 2)); // 0.00
我也面临着同样的问题,并决定在TS中使用字符串操作。
如果没有足够的小数,它将返回原始值
const getDecimalsWithoutRounding = (value: number, numberOfDecimals: number) => {
const stringValue: string = value?.toString();
const dotIdx: number = stringValue?.indexOf('.');
if (dotIdx) {
return parseFloat(stringValue.slice(0, dotIdx + numberOfDecimals + 1));
} else {
return value;
}
};
console.log(getDecimalsWithoutRounding(3.34589, 2)); /// 3.34
console.log(getDecimalsWithoutRounding(null, 2)); ///null
console.log(getDecimalsWithoutRounding(55.123456789, 5)); /// 55.12345
console.log(getDecimalsWithoutRounding(10, 2)); /// 10
console.log(getDecimalsWithoutRounding(10.6, 5)); /// 10.6