繁体   English   中英

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() ,但是Math.abs()却使它太远了。

.toFixed()对我不起作用,因为如果数字只有2 .toFixed()数,它将在末尾添加其他零。 我只想显示第四位(如果计算得出)。

只需扩展@ 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. 然后将小数部分修整为两位数(或任意多个)。
  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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM