JSFiddle - React, Tailwind, and code Playground
by hicurin
JavaScript
var num = 1.256576;
function decimalPlaces(num) {
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(
0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0)
// Adjust for scientific notation.
- (match[2] ? +match[2] : 0));
}
if(decimalPlaces(num) < 2){
num = num.toFixed(2);
}
alert(num);