How to round a decimal value within an object using Javascript

I am a beginner in JavaScript and am encountering an issue with rounding decimal numbers. I have an object with multiple key value pairs where the values can be strings, numbers, or null. My goal is to target the number key value pairs and round the number values to 2 decimal places. For example, if the value is 1.798, I want to round it to 1.80. Since I don't know how many key value pairs will be in my object, I just want to focus on the number values and update them.

I attempted using a forEach loop but later realized it works only on arrays.

var obj = {
    name: 'abc',
    term1: 0,
    term2: 1.798,
    term3: 1.9999,
    term4: 0,
    term5: null,
    term6: 'xyz'
};


// Expected output

var obj = {
    name: 'abc',
    term1: 0,
    term2: 1.80,
    term3: 2.00,
    term4: 0,
    term5: null,
    term6: 'xyz'
};

Answer №1

Utilize the typeof function to distinguish numbers and use .toFixed(n) method to round to n decimal places (ensuring trailing 0s are not lost when returned as a string).

let data = {
    title: 'example',
    value1: 2,
    value2: 3.14159,
    value3: 5.6789,
    value4: 0,
    value5: null,
    value6: 'testing',
};
for(key in data){
    if(typeof data[key] === 'number'){
        data[key] = data[key].toFixed(2);
    }
}
console.log(data); // Object { title: "example", value1: "2.00", value2: "3.14", value3: "5.68", value4: "0.00", value5: null, value6: "testing" }

Answer №2

It's important to note that trailing zeros are not considered significant digits in numbers. To maintain the zeros, you can convert the number into a string.

var obj = {
    name: 'abc',
    term1: 0,
    term2: 1.798,
    term3: 1.9999,
    term4: 0,
    term5: null,
    term6: 'xyz'
};

Object.entries(obj).forEach(([key, value]) => {
  if(typeof value === 'number') {
    // obj[key] = value.toFixed(2) // 1.9999 -> "2.00"
    obj[key] = +value.toFixed(2) // 1.9999 -> 2
  }
})

console.log(obj)

Answer №3

To iterate through the keys and make decisions, you can utilize the Object.keys(obj) method. Below is a functional solution tailored to address your issue:

var obj = {

name: 'abc', term1: 0, term2: 1.798, term3: 1.9999, term4: 0, term5: null, term6: 'xyz'

};

for(var key of Object.keys(obj)) {
    if(typeof obj[key] === 'number' && obj[key] !== 0) {
    obj[key] = (Math.round(obj[key] * 100)) / 100;
  }
}

You can test this code in action using this JSFiddle link: https://jsfiddle.net/x4otdeca/

Answer №4

In order to achieve the desired outcome, utilize a for loop to iterate through the object.

  1. Use a for-in loop to iterate through the object
  2. Check if each value is null or a string, then use the toFixed(2) method to round decimal values
    var obj = {
      name: 'abc', 
      term1: 0, 
      term2: 1.798, 
      term3: 1.9999, 
      term4: 0, 
      term5: null, 
      term6: 'xyz'
    };
    
    for( let key in obj){
       obj[key] = !obj[key] || isNaN(obj[key])? obj[key] : obj[key].toFixed(2)
    }
    
    console.log(obj)

Find this code on CodePen - https://codepen.io/nagasai/pen/dybNwEW?editors=1010

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

Performing a Jquery ajax request within a success callback

I have a situation where I am making an AJAX call inside the success function. While trying to append data to a hidden field in the second AJAX call, I noticed that when I put the alert outside the second AJAX call, the hidden field appears empty. Why is ...

Avoiding multiple ajax requests due to multiple clicks

I have a blog on WordPress that has a jQuery code allowing users to click a bookmark link to save the post as a bookmark. Each post displays a total bookmark counter in this format: "Bookmarked (5)". The issue is that when a user clicks multiple times on t ...

How to populate a database with Facebook data by utilizing AJAX post and PHP

I've been developing a Facebook Canvas game and had it running smoothly on my localhost along with a local database via phpMyAdmin. However, after moving it online, I've encountered an issue with the database. Previously, the game would grab pla ...

Is there a way to determine what is affecting the properties of an element?

I've been grappling with a chunk of lengthy HTML, styles, and javascript. My mission? To uncover whatever magic is changing the text within a specific element. <span class="panel-title"> I'm a Panel with All Options</span> Transform ...

Is there a way to execute a script during every npm install process?

Is it possible to set up pre-push hooks for Git with each npm install action? Are there any alternative solutions that do not involve installing tools like Gulp, and instead rely solely on npm? ...

Navigate to a fresh HTML page upon form submission

I'm completely new to the world of web apps and JavaScript, and I'm facing an issue where my form submission doesn't redirect me to a thank you page. Instead, it just leads to a blank page every time. I've tried researching solutions on ...

Error message: The variable THREE has not been defined in a Rails Project utilizing the threejs-rails gem

Currently, I am working on a project using Ruby on Rails and incorporating three.js. I have successfully installed the corresponding gem, and everything appears to be functioning properly. However, an error is being thrown in the JavaScript: Uncaught Refe ...

How can the Singleton pattern be properly implemented in Typescript/ES6?

class Foo{ } var instance: Foo; export function getFooInstance(){ /* logic */ } or export class Foo{ private static _instance; private constructor(){}; public getInstance(){/* logic */} } // Use it like this Foo.getInstance() I would ...

Turn off Babel's strict mode when transpiling JavaScript files

Currently, I am facing an issue while trying to transpile a set of JavaScript files using Babel. Since Babel operates in strict mode by default, it triggers a syntax error whenever there is a conflict like the use of the delete keyword. The solution I am s ...

Collaborate on sharing CSS and TypeScript code between multiple projects to

I am looking for a solution to efficiently share CSS and TS code across multiple Angular projects. Simply copy-pasting the code is not an ideal option. Is there a better way to achieve this? ...

An issue encountered when utilizing the express routes method within a NodeJS application

I'm running into an issue while attempting to restructure my NodeJS API, specifically when it comes to importing my routes. The error I'm encountering is as follows: /Users/pato/Documents/nodejs-bp-api/node_modules/express/lib/router/index.js:13 ...

Angular: directive modifying the value of a form control

I have implemented a feature to automatically transform the slug when the user inputs the name in a control field. This transformation includes changing spaces to hyphens (-) among other things. Although I created a directive for this purpose, it seems to ...

Instructions for developing a tailored database solution State Storage Adapter for the Microsoft Bot Framework

As I work on creating a custom adapter for integrating a specific database with the Microsoft Bot framework, my approach is to develop something similar to the cosmosDBPartitionedStorage class within the bot framework. From my analysis, it seems that ther ...

JS issue: Having trouble accessing the array values despite the array being present

I am working on an ajax call where I save the success data in an array. However, when I try to access that data outside of the ajax function and use console to log my array, it appears as expected. Here is a glimpse at what I see on the screen: https://i ...

Instead of loading the HTML into the div, Ajax is now sending me the link instead

I have just begun working on a new laravel project and am currently working on the user profile page, which will include a sidebar with links like Portfolio, Account Settings, etc. My goal is to dynamically load each page into a div when a link in the side ...

Troubleshooting Angular Virtual Scrolling and Browser Animation Render Glitch

Encountering issues with browser animations and cdkVirtualScrolling resulting in render bugs. Check out this example for reference: https://stackblitz.com/edit/angular-ivy-nutyca?file=src/app/app.module.ts Upon clicking the "toggle list" button, observe ...

The tooltip function seems to be disabled when I import Bootstrap using npm

I am facing an issue on my webpage related to including Bootstrap JS using npm. When I include it like this: <script src="node_modules/jquery/dist/jquery.slim.min.js"></script> <script src="node_modules/popper.js/dist/umd/popp ...

Unexpectedly, Visual Studio Code extensions have ceased to function

Recently, I encountered an issue with my Visual Studio Code. After shutting down my computer while VS Code was still open, all the extensions stopped functioning when I powered it back on. These extensions are crucial for my React and Typescript project, ...

What is the best way to adjust the equal right padding or margin in the header for both IOS and Android using React Navigation options?

To ensure an equal gap on both sides for both IOS and Android platforms, I utilized a combination of techniques. For the right side, I achieved this using a minus margin, positive padding, and Platform. <Stack.Navigator screenOptions={{ contentSty ...

When converting an abstract syntax tree into a React component, the Cyrillic characters are transformed into Unicode escape sequences

Every text that isn't in Latin characters seems to do this. I'm trying to include an attribute called "attrName" with the value of "киррилица" to the button: <button attrName="киррилица">текст</button> ...