ECMAScript 6 offers Math.trunc method for completely consistent truncation. If you have a number then use this method to truncate decimal in JavaScript.
JavaScript Math module trunc() function returns the integer part of a number by removing any fractional digits.
Syntax of Math.trunc()
Math.trunc(x)
Example of JavaScript truncate decimal
See below example doesn’t do any rounding, it simply removes all the digits following the decimal.
Note: Math.trunc()
isn’t supported on all platforms yet (namely IE), but you could easily use a polyfill in the meantime.
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript">
var num = 98.33668;
var n = Math.trunc(num);
alert(n);
</script>
</body>
</html>
Output:
Q: How to truncate decimal to 2 places in JavaScript?
Answer: use method round and toFixed as below.
(Math.round(num * 100) / 100).toFixed(2);
Note that it will round to 2 decimal places, so the input 1.746
will return 1.75
.
Do comment if you have any questions and suggestion on this tutorial.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version