Math.abs() 限制小数位数

Math.abs() Limit the amount of deimals

我已经搜索了互联网,但还没有找到真正适合我的解决方案。

var tv = Length * Type;

if (tv < 0) 
    {
    cForm.voltage.value = "-" + Math.abs(tv) + " V";
    }
else...

出于某种原因,使用这两个数字进行的某些计算结果大约为小数点后第 15 位。我想限制返回的小数位数,并且不允许数字向上或向下舍入。在计算器上,它只能计算出小数点后第三位,但 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));

我确定这不是最有效的方法,但它很无脑 -

  1. 获取结果
  2. 根据小数点拆分成数组
  3. 然后 trim 将小数部分保留为两位数(或者您想要的位数)。
  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