如何在javascript中获得十进制长度到小数点后6位?



我正在编写代码,经过一些算术后四舍五入到小数点后六位。我正在循环遍历数组的内容并找出数组的内容。然后除以数组长度。我找到了固定的函数。我设置为固定(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)