Home > database >  I need a simple code to remove decimal in my javascript
I need a simple code to remove decimal in my javascript

Time:04-03

Here is my code. this showing a result with 8-9 decimal after main number. I want only 2 decimal to show after main number.

var data = resp.data
Object.keys(data).map(q => {
  Object.keys(data[q]).map(r => {
    console.log($('.rate_'   r   '_'   q), data[q][r])
    $('.rate_'   r   '_'   q).text(data[q][r]   '%')
  })
})

CodePudding user response:

You can just use toFixed() to do that with the parameter being the number of digits after the decimal point. That assumes you have a Number already. If you have a string you need to parse it first using Number.parseFloat().

const test = 23213423.23423423;
console.log(test.toFixed(2));

const testStr = "23213423.23423423";
const parsed = Number.parseFloat(testStr);
if (!isNaN(parsed)) console.log(parsed.toFixed(2));
else console.log("The string is not a number!");

CodePudding user response:

working example

const data = {
  a: { aa: 10.1234}, 
  b: {bb: 1.12345}
};

const out = [];
Object.keys(data).map( q => {
  Object.keys(data[q]).map( r => {        
    out.push(data[q][r].toFixed(2))
  })
})

console.log(out)

CodePudding user response:

Here is a way using Math.round

const numbers = [
   1.1234567,
   10.14,
   0,
   44.178,
   15.1,
   23445.212124,
   2373872387283
];

numbers.forEach(x => {
   const result = Math.round(x * 100) / 100;
   console.info(result);
});

CodePudding user response:

Syntax

Math.round(x)

Parameters

x -> A number

Return value

The value of the given number is rounded to the nearest integer.

const data = {
  a: {aa: 10.4234}, 
  b: {bb: 1.52345},
  c: {cc:708.957}
};

Object.keys(data).map(q => {
  Object.keys(data[q]).map(r => {
    console.log(`Rate of ${q}: {${r}: ${Math.round(data[q][r])}}`)
  })
})

  • Related