What is the best way to achieve a precision of 6 decimal places in JavaScript when working with decimals?

While working on coding to round numbers to six decimal places after performing some arithmetic operations, I encountered a problem. I was iterating through the elements of an array and conducting calculations based on the array contents. To achieve rounding to six decimal places, I used the toFixed function with a parameter of 6. However, when dividing the array contents by the array length and applying toFixed(6), I noticed that only one decimal place was being displayed instead of six.

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++;
      
    } else if (array[i] < 0) {

      negative_count++;
     
    } else if (array[i] == 0) {

      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);

Answer №1

Allow me to clarify the process occurring within 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) this will lead to an error.

var calculateNeg = negative_count/array.length.toFixed(6); //    2 / 5.toFixed(6) this will result in an error.
  
var calculateZero = zero_count/array.length.toFixed(6);  //      0 / 1.toFixed(6)  this will cause an error.

Here's what you need to adjust:

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

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

If you want to convert these strings back to numbers, you can utilize parseFloat(string).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to combine two DIV table rows within Bootstrap 5?

Looking at the code below, there are 6 cells in 2 rows, but I want to merge cell number "2" and "5". I know this can be accomplished using CSS Table DIV, but is there a way to do it with Bootstrap? I haven't found any documentation that worked for me ...

Retrieving the link to share for every video located in the Dropbox folder

My Dropbox folder contains a set of videos labeled "v1.avi, v2.avi, ....., vn.avi". I am looking to automate the process of extracting the share link for each video in the folder so that I can easily use it as a source value for HTML video. . . . Is ther ...

What are the steps to retrieve all memcached information using node.js?

One of my main objectives is to have the user session data expire when they close their browser. However, I am facing a challenge because my Server depends on memcached to function correctly. Therefore, I need to find a way to specifically delete the use ...

Library for Nodejs that specializes in generating and converting PDF/A files

Is there a library available that can convert/create a PDF/A file? I've been searching for solutions but the existing answers suggest using an external service or provide no response at all. I heard about libraries in other languages like ghostscriptP ...

Guide on Updating the ColModel Dynamically in JAVASCRIPT/HTML using clearGridData, setGridParam, and reloadGrid Functions

I am trying to figure out how to dynamically change the colmodel of my grid using a function that is called by a SELECT. The reason for this is because my grid has different periods and needs to display either cost or tons based on user selection. Below i ...

Exploring React Native Networking using react-native-router-flux

Hello everyone, I have a quick query. I am looking to assign each Button to a different page. import React, { Component } from 'react'; import { ActivityIndicator, FlatList, Text, View, TouchableOpacity } from 'react-native'; export ...

Utilize React without integrating a router component

For my web application built with reactjs, I am considering creating a multi-page site rather than a single page. Should I bundle all the react code into one file and include it on every page of the application, then utilize the exposed function to render ...

In Javascript, a variable is being defined by combining a string with another variable through concatenation

Hey, I'm relatively new to working with Javascript and am facing an issue that I believe can be resolved easily with the right syntax. The problem lies in setting a variable (totalRow1) where it needs to be concatenated with a string and another vari ...

The perplexing results received when using the npm outdated command

Could someone provide an explanation for the meaning behind this output? $ npm --version 3.10.8 $ npm -g outdated npm Package Current Wanted Latest Location npm 3.10.8 4.0.2 3.10.9 As stated in the documentation, the "Wanted" column should d ...

What is the best way to showcase a ul element as inline-block?

Is there a way to keep the bottom menu aligned in one row on all screen sizes? I attempted using display: inline-block, but it doesn't seem to work for me. Below is the CSS code: footer #middle-footer { background: #F6F6F6; color: #000; font-size ...

Acquiring Device Data in React-Native for iOS

Hello, I am currently attempting to retrieve device information from an iPad. I attempted to use the library found at https://github.com/rebeccahughes/react-native-device-info, however, it caused issues after performing a pod install. My main goal is to ob ...

What is the best way to create hover effects on buttons in Vue.js 3?

I'm currently developing a calculator to practice my Vue.js 3 skills (I am new to vue). I've successfully implemented the basic features, but now I'm exploring how to incorporate hover animations on the buttons. Specifically, I want to diffe ...

Showing a property only as you scroll through the page

Seeking assistance on creating a scrolling effect for a box shadow property using HTML, CSS, and JS. The goal is to have the shadow appear with a subtle transition while scrolling and then disappear when scrolling stops. Here's the code I've be ...

Issue with Material UI Menu positioning incorrectly when button is aligned to the right or left

When looking at the first image, it appears that the material-UI menu position is working correctly. However, when we change the button position to align-right, the menu position shifts slightly to the left, not perfectly aligning with the right side as in ...

Using Jquery to store input values from within <td> elements in an array

I'm trying to capture user input from a dynamically changing table with 2 columns. How can I retrieve the data from each column separately? The size of the table is adjusted by a slider that controls the number of rows. Below is the structure of my ta ...

Greetings! I am looking for information on how to activate CORS in a Ruby on Rails API application deployed on OpenShift for use with an Angular

My current setup involves a script utilizing Angular to display records fetched from a Rails API REST, which is hosted in OpenShift. In my public/.htaccess file, I have included the following directives: Header add Access-Control-Allow-Origin "*" Header a ...

Learn how to dynamically set the "selected" option in Vue based on object data

I've done some digging on SO but haven't found exactly what I need. So, here's the situation - I've got a sorting function in progress. I have an array of date ranges (PayPeriods) that I want to render into a select with option compone ...

The dynamic value feature in Material UI React's MenuItem is currently experiencing functionality issues

Whenever I use Select in Material UI for React, I encounter an issue where I always receive undefined when selecting from the drop-down menu. This problem seems to occur specifically when utilizing dynamic values with the MenuItem component. If I switch to ...

What is the best way to access a video stored in a local file on the initial page and then watch it on the subsequent

I recently encountered a scenario where I needed to select a video on one page and have it automatically play on another page without any redirection. The initial page displays a list of videos for selection, like this: FirstPage Once a video is chosen on ...

Issue encountered while subscribing to SalesForce topic using Node.js

Attempting to subscribe to a SalesForce topic through a Node.js server using the code provided in the JSForce documentation: conn.streaming.topic("InvoiceStatementUpdates").subscribe(function(message) { console.log('Event Type : ' + message.ev ...