xxxxxxxxxx
(<number>).toFixed(<Number of decimal places required>);
xxxxxxxxxx
var example = 3.35464464374256 ;
example = parseFloat(example.toFixed(2)) ; // example == 3.35
xxxxxxxxxx
const number = 42.56789;
const numberWithTwoDecimals = number.toFixed(2);
console.log(numberWithTwoDecimals); // Output: "42.57"
xxxxxxxxxx
// To force decimal to use only two numbers after coma, you can use this
var numberOne = 4.05;
var numberTwo = 3;
// If you use only this :
var total = numberOne * numberTwo; // This will be 12.149999999999999 (thanks JS...)
// But if you use this :
var total = Number(numberOne * numberTwo).toFixed(2); // This will be 12.15
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