我已经浏览了互联网,但我找不到真正适用于我的解决方案。
var tv = Length * Type;
if (tv < 0)
{
cForm.voltage.value = "-" + Math.abs(tv) + " V";
}
else...
由于某种原因,这两个数字的一些计算出现在大约十五分之一。我想限制返回的小数,并且不允许数字向上或向下舍入。在一个计算器上它只出现在大约第三个小数点,但Math.abs()
带来的太远了。
.toFixed()
对我不起作用,因为如果数字只有2位小数,它将在末尾添加额外的零。如果计算,我只想显示第四个。
只需扩展@ goto-0的注释,使用正确的小数位数。
var tv = Length * Type;
if (tv < 0)
{
cForm.voltage.value = "-" + (Math.round(Math.abs(tv) * 10000) / 10000) + " V";
}
else...
这是作为一个截断额外小数位的函数的实现。如果你想围绕输出,你可以使用Number.toPrecision()
。
function toFixedDecimals(num, maxDecimals) {
var multiplier = Math.pow(10, maxDecimals);
return Math.floor(num * multiplier) / multiplier
}
console.log(toFixedDecimals(0.123456789, 4));
console.log(toFixedDecimals(100, 4));
console.log(toFixedDecimals(100.12, 4));
我敢肯定它不是最有效的方法,但它很无脑 -
抱歉长变量名称 - 只是试图弄清楚发生了什么:)
// your starting number - can be whatever you'd like
var number = 145.3928523;
// convert number to string
var number_in_string_form = String(number);
// split the number in an array based on the decimal point
var result = number_in_string_form.split(".");
// this is just to show you what values you end up where in the array
var digit = result[0];
var decimal = result[1];
// trim the decimal lenght to whatever you would like
// starting at the index 0 , take the next 2 characters
decimal = decimal.substr(0, 2);
// concat the digit with the decimal - dont forget the decimal point!
var finished_value = Number(digit + "." + decimal);
在这种情况下,finished_value将= 145.39