'I need a simple code to remove decimal in my javascript
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] + '%')
})
})
Solution 1:[1]
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!");
Solution 2:[2]
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)
Solution 3:[3]
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);
});
Solution 4:[4]
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])}}`)
})
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Maik Lowrey |
| Solution 3 | Leo |
| Solution 4 | Dip Vachhani |
