繁体   English   中英

如何在javascript中将小数长度设置为小数点后6位?

[英]How do I get the decimal length to 6 decimal places in javascript?

经过一些算术运算,我正在编写代码以四舍五入到小数点后六位。 我正在遍历数组的内容并找出数组的内容。 然后我将它除以数组长度。 我找到了 toFixed 的功能。 我设置为固定(6)。 举个例子。 arraycontents/array.length.toFixed(6) 应该得到小数点后六位。 我只得到1?

 array = [1, 1, 0, -1, -1]; var positive_count = 0; var negative_count = 0; var zero_count = 0; function plusMinus(array) { for(var i = 0; i < array.length; i++) { if(array[i] > 0) { positive_count++; //console.log("Positive Count " + positive_count); } else if (array[i] < 0) { negative_count++; //console.log("Negative Count " + negative_count); } else if (array[i] == 0) { zero_count++; // console.log("Zero count " + zero_count); } } var calculatePos = positive_count/array.length.toFixed(6); calculatePos.toFixed(6); console.log(calculatePos); var calculateNeg = negative_count/array.length.toFixed(6); console.log(calculateNeg); var calculateZero = zero_count/array.length.toFixed(6); console.log(calculateZero); } plusMinus(array);

让我快速解释一下您的代码逻辑中发生了什么:

array.length // 5
positive_count = 2;
negative_count = 2;
zero_count = 1;

var calculatePos = positive_count/array.length.toFixed(6); //    2 / 5.toFixed(6) the result should be an error.

var calculateNeg = negative_count/array.length.toFixed(6); //    2 / 5.toFixed(6) the result should be an error.
  
var calculateZero = zero_count/array.length.toFixed(6);  //      0 / 1.toFixed(6)  the result should be an error.

你应该做什么:

var calculatePos = (positive_count/array.length).toFixed(6); // => '0.400000' string

var calculateNeg = (negative_count/array.length).toFixed(6); // => '0.400000' string
  
var calculateZero = (zero_count/array.length.toFixed(6);  //    => '0.000000' string

如果您希望将类型转换为数字,可以使用parseFloat(string)来完成。

暂无
暂无

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

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