Adding Floating Point Numbers in TypeScript Objects

Recently, I've been encountering some strange results while trying to sum up my floating point values. The output seems off with 8 decimal places and other unexpected outcomes. All I really want to do is add up the protein values of various objects to achieve a sum, like aiming for 200.1.

**

DATA

**

**

[{"upload_date":"2019-12-31T21:41:42.943Z","item":"hot_dog","protein_content":"10.00","carb_content":"25.00","fat_content":"15.00","calories":"1170.00"},{"upload_date":"2019-12-31T21:41:56.604Z","item":"fried_rice","protein_content":"3.50","carb_content":"64.30","fat_content":"28.00","calories":"2188.00"},{"upload_date":"2019-12-31T21:43:06.372Z","item":"greek_salad","protein_content":"6.60","carb_content":"10.30","fat_content":"19.40","calories":"1079.00"},{"upload_date":"2019-12-31T21:42:56.577Z","item":"fried_rice","protein_content":"3.50","carb_content":"64.30","fat_content":"28.00","calories":"2188.00"},{"upload_date":"2019-12-31T21:42:45.559Z","item":"steak","protein_content":"25.10","carb_content":"0.00","fat_content":"0.50","calories":"445.00"},{"upload_date":"2019-12-31T21:42:28.609Z","item":"hot_dog","protein_content":"10.00","carb_content":"25.00","fat_content":"15.00","calories":"1170.00"},{"upload_date":"2019-12-31T21:42:15.793Z","item":"steak","protein_content":"25.10","carb_content":"0.00","fat_content":"0.50","calories":"445.00"},{"upload_date":"2019-12-31T21:42:05.049Z","item":"greek_salad","protein_content":"6.60","carb_content":"10.30","fat_content":"19.40","calories":"1079.00"}]

CODE

**

for(let i = 0; i < dietInfo.length; i++) {
     this.protein +=  dietInfo[i].protein_content
     this.calories += parseFloat(dietInfo[i].calories)
     this.carbs += parseFloat(dietInfo[i].carbs_content)
     this.fat += parseFloat(dietInfo[i].fat_content)
    //  this.protein = parseFloat(this.protein).toFixed(1)
}
console.log('before:', this.protein);
// round of inaccuracies, assuming decimals
this.protein = Math.round(this.protein*100000000)/100000000;
console.log('after:', this.protein);

Answer №1

Dealing with JavaScript floating point calculations can be tricky due to inaccuracies, which are highlighted in this particular issue.

To bypass these issues, one approach is to round off the values to a specific digit. Here's an example using some dietary information:

const dietInfo =  [{"upload_date":"2019-12-31T21:41:42.943Z","item":"hot_dog","protein_content":"10.00","carb_content":"25.00","fat_content":"15.00","calories":"1170.00"},{"upload_date":"2019-12-31T21:41:56.604Z","item":"fried_rice","protein_content":"3.50","carb_content":"64.30","fat_content":"28.00","calories":"2188.00"},{"upload_date":"2019-12-31T21:43:06.372Z","item":"greek_salad","protein_content":"6.60","carb_content":"10.30","fat_content":"19.40","calories":"1079.00"}];

const {protein, calories, carbs, fat} = dietInfo.reduce((res, entry) => ({ 
     res.protein += +entry.protein_content,
     res.calories += +entry.calories,
     res.carbs += +entry.carb_content,
     res.fat += +entry.fat_content
}), {protein: 0, calories: 0, carbs: 0, fat: 0});

// A custom function for rounding off to a specific digit
const roundToDigit = (num, digits) => (Math.round(num * Math.pow(10, digits) + Number.EPSILON) / Math.pow(10, digits)); 

this.protein = roundToDigit(protein, 1);
this.calories = roundToDigit(calories, 1);
this.carbs = roundToDigit(carbs, 1);
this.fat = roundToDigit(fat, 1);

Answer №2

If you want to aggregate your existing dataset, one way is to utilize the Array.reduce method to sum up the values. The code snippet below showcases an example where protein, carbs, fat, and calories are accumulated into an object.

const data = [{"upload_date":"2019-12-31T21:41:42.943Z","item":"hot_dog","protein_content":"10.00","carb_content":"25.00","fat_content":"15.00","calories":"1170.00"},{"upload_date":"2019-12-31T21:41:56.604Z","item":"fried_rice","protein_content":"3.50","carb_content":"64.30","fat_content":"28.00","calories":"2188.00"},{"upload_date":"2019-12-31T21:43:06.372Z","item":"greek_salad","protein_content":"6.60","carb_content":"10.30","fat_content":"19.40","calories":"1079.00"},{"upload_date":"2019-12-31T21:42:56.577Z","item":"fried_rice","protein_content":"3.50","carb_content":"64.30","fat_content":"28.00","calories":"2188.00"},{"upload_date":"2019-12-31T21:42:45.559Z","item":"steak","protein_content":"25.10","carb_content":"0.00","fat_content":"0.50","calories":"445.00"},{"upload_date":"2019-12-31T21:42:28.609Z","item":"hot_dog","protein_content":"10.00","carb_content":"25.00","fat_content":"15.00","calories":"1170.00"},{"upload_date":"2019-12-31T21:42:15.793Z","item":"steak","protein_content":"25.10","carb_content":"0.00","fat_content":"0.50","calories":"445.00"},{"upload_date":"2019-12-31T21:42:05.049Z","item":"greek_salad","protein_content":"6.60","carb_content":"10.30","fat_content":"19.40","calories":"1079.00"}];

const result = data.reduce( (acc, curr) => {
  acc.protein_content += parseFloat(curr['protein_content']);
  acc.carb_content += parseFloat(curr['carb_content']);
  acc.fat_content += parseFloat(curr['fat_content']);
  acc.calories += parseFloat(curr['calories']);
  return acc;
}, {protein_content: 0, carb_content: 0, fat_content: 0, calories: 0});

console.log(result);

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

Preparing data before using Kendo UI upload function is essential

I need to pass a data (specifically a GUID) to the upload method of the kendoUpload, so that a particular MVC Controller action method can receive this data each time the upload occurs. $("#propertyAttachmentUpload").kendoUpload({ async: { ...

Initiate an Ajax form submission to dynamically update the contents of a

For my project, I've set up a main page specifically for document creation in the DocumentsController. Users have the ability to alter the status of the document on this page. If the status is NEW, users are permitted to add a new device (referred to ...

No responses received for my post on Node Express - a newbie in the world of Node

My current task involves utilizing an Axios post function to send multipart form data to a Node.js Express endpoint using Multiparty for input field processing. Upon receiving the data, the endpoint saves it in the database. I am looking to utilize the re ...

Adding to object in an external JSON file using javascript

I am working with an external file called file.json which contains the following values: { "number": "value" } My goal is to run a function that will append new data to the existing file instead of overwriting it. For instance, after running the func ...

Establish the following 13 steps to configure the initial server state and retrieve the client state

Currently, I have 13 applications and I am utilizing Zustand as my state manager. Below is a simple layout example: <MainProvider> <div className="min-h-screen flex flex-col"> <Navbar></Navbar> <main className ...

Divide the string into two halves and display them in separate div elements

I am in need of a code that can split a string in half. For instance, if the inputted name is "Trishy", which consists of 6 letters, the first 3 letters should be placed into the second li within the <ul class="hardcover_front">, while the remaining ...

Integration of NextAuth with Typescript in nextjs is a powerful tool for authentication

I am diving into NextAuth for the first time, especially with all the new changes in Nextjs 13. Setting up nextauth on my project seems to be a daunting task. I have gone through the documentation here I am struggling to configure it for nextjs 13. How do ...

The client using socket.io is receiving events for "double plus one"

While experimenting with socketio, I encountered a bug that others are experiencing as well but I haven't been able to find a valid solution. This is the server-side code: const app = require('express')(); const server = require('http& ...

Several jquery libraries are experiencing malfunctions

<head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $(".slidingDiv").hide(); $(".show_hide").show().click ...

Choose a word at random from a JSON string

Utilizing JSONP, I have successfully retrieved a list of words from an external source to randomly select one for use in a game. The current source being used is as follows: function processResult(obj) { console.log(obj); var data = ...

What is the best way to associate dates with a particular ID within a textfield's value?

I am working with an array of objects called dates, and each object in the array looks like this: {id: 9898, date: 10/06/2020}. Within this array, there are multiple objects with the same id, and I want to display dates with the same id in a TextField com ...

SQL AJAX Query Form

I have been searching for tutorials on how to create a good form with PHP and AJAX. I tried starting with a code given to me by a friend and managed to send the request successfully. However, it seems like the data I receive is empty. Could you please take ...

Firebase firestore is reporting an error stating that the requested document cannot be found

Using nodejs, I am working on creating firestore documents in a specific structure that includes the collection name followed by an ID and then the document itself. While my code successfully adds the document, it does not create the parent document (ID) i ...

Managing the creation of a fresh VueJs object with checkboxes enabled for CRUD operations

Hello fellow developers! I am currently working on a shop card project and I'm looking to add a new product to the collection of sale elements. Let's consider the JSON structure retrieved from the backend: "products": [ { "product_prov ...

Struggling to comprehend the node.js walker concept

I am struggling to grasp the concept of how the signature/header of the node.js walker functions. I understand that a walker can go through a directory and apply filters, but I'm unsure about how the signature of the .on function works. For example: ...

Managing a two-dimensional array in AngularJS: tips and tricks

I have a JSON source that provides me with a double array: // Function and module code omitted .. $scope.texts = [ ['Small sheep and ham.'], ['Ducks go moo.', 'Helicopters and racecars go bang!'] ]; My goal is to display ...

Pairing TMDb genre IDs and their respective names using JavaScript within the Ember.js framework

If you've ever worked with the TMDb (The Movie Database) api for movies, you might have encountered this issue. I am struggling to display the genre names for each movie shown. My goal is to replace the numbers in genre_ids from the movies api with th ...

Custom AngularJS directive for ensuring the selection of a required HTML element

Today brings another question as I continue working on my web application. I've encountered an issue with the 'required' attribute not being widely supported in major browsers. The attribute only works if the first option value is empty, whi ...

Stripping away AM | PM from date variables

Is there a way to accurately calculate the difference between two datetime values in minutes without including AM|PM? When attempting to trim out the AM | PM from my code, I encounter errors (specifically NaN minutes). How can I safely remove this element ...

Issue with retrieving query results using node_redis client

I've been struggling with a particular issue that I just can't seem to solve. The problem revolves around not being able to retrieve output values from a Redis query. My setup involves using the node_redis client as the Redis driver for my Node.J ...