Reputation: 21
I am displaying dimensions for ad to be published in newspaper, the height / width seems to use millimetres with incredibly small decimals like x.0002mm, I want numbers to be rounded down (always down, never up) to the nearest whole mm?
For example,
Input -> height: 380.0002mm width: 262.0002mm
expected Output-> height: 380mm width: 262mm
I already tried .toFixed()
, but it is not working for large decimal inputs
For example,
sample Input -> height: 380.1252mm width: 262.6592mm
expected Output-> height: 380.1252mm width: 262.6592mm
I want number to be round down only if decimal number is very small for ex: 380.0002, I want to avoid rounding down if decimal number is greater, for ex: 380.1252
Upvotes: 1
Views: 1202
Reputation: 465
This should work for you
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));
}
var length = (num + '').replace('.', '').length; // for floats
console.log(length);
if (num.toPrecision(length).includes(".00")){
num = Math.floor(num);
console.log(num)
}else{
var dec = decimalPlaces(num);
num = num.toFixed(dec);
console.log(num)
}
And BTW Credit for decimalPlaces() function: Javascript: How to retrieve the number of decimals of a string number?
Upvotes: 0
Reputation: 465
Check this link, Formatting numbers for decimals
var number = 380.0002
number.toPrecision(6) //returns 380.000 (padding)
number.toPrecision(4) //returns 380.0 (round up)
number.toPrecision(3) //returns 380
Math.floor(380.0002) //returns 380
Upvotes: 2