xxxxxxxxxx
const number = 42.56789;
const numberWithTwoDecimals = number.toFixed(2);
console.log(numberWithTwoDecimals); // Output: "42.57"
xxxxxxxxxx
var myNumber = 2;
myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"
xxxxxxxxxx
const number = 3.14159265359;
const formattedNumber = number.toFixed(2);
console.log(formattedNumber); // Output: 3.14
xxxxxxxxxx
Use toFixed to convert it to a string with some decimal places shaved off, and then convert it back to a number.
+(0.1 + 0.2).toFixed(12) // 0.3
It looks like IE's toFixed has some weird behavior, so if you need to support IE something like this might be better:
Math.round((0.1 + 0.2) * 1e12) / 1e12
xxxxxxxxxx
var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;
xxxxxxxxxx
// Example 1: Adding decimal to a whole number
let num = 5;
let decimal = 0.5;
let result = num + decimal;
console.log(result); // Output: 5.5
// Example 2: Adding decimal to a floating-point number
let floatingNum = 3.14;
let additionalDecimal = 0.86;
let updatedNum = floatingNum + additionalDecimal;
console.log(updatedNum); // Output: 4