mustyg123
mustyg123

Reputation: 27

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

I am writing code to round to six decimal places after some arithmetic. I am looping through the contents of an array and finding out the contents of the array. Then I divide it by the array length. I found the function toFixed. I am setting toFixed(6). So for example. arraycontents/array.length.toFixed(6) Should get six places after the decimal. I am only getting 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);

Upvotes: 1

Views: 6306

Answers (1)

jkalandarov
jkalandarov

Reputation: 685

Let me quickly explain what is happening in your code logic:

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.

What you should do:

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

If you wish to convert the types to a number, you can do it with parseFloat(string).

Upvotes: 3

Related Questions