47 lines
1.3 KiB
JavaScript
47 lines
1.3 KiB
JavaScript
/**
|
|
* Calculates a number's precision based on the number of trailing
|
|
* zeros if the number does not have a decimal indicated by a negative
|
|
* precision. Otherwise, it calculates the number of digits after
|
|
* the decimal point indicated by a positive precision.
|
|
* @param value - the value to determine the precision of
|
|
*/ "use strict";
|
|
Object.defineProperty(exports, "__esModule", {
|
|
value: true
|
|
});
|
|
function _export(target, all) {
|
|
for(var name in all)Object.defineProperty(target, name, {
|
|
enumerable: true,
|
|
get: all[name]
|
|
});
|
|
}
|
|
_export(exports, {
|
|
calculatePrecision: function() {
|
|
return calculatePrecision;
|
|
},
|
|
precisionRound: function() {
|
|
return precisionRound;
|
|
}
|
|
});
|
|
function calculatePrecision(value) {
|
|
/**
|
|
* Group 1:
|
|
* [1-9]([0]+$) matches trailing zeros
|
|
* Group 2:
|
|
* \.([0-9]*) matches all digits after a decimal point.
|
|
*/ const groups = /[1-9]([0]+$)|\.([0-9]*)/.exec(String(value));
|
|
if (!groups) {
|
|
return 0;
|
|
}
|
|
if (groups[1]) {
|
|
return -groups[1].length;
|
|
}
|
|
if (groups[2]) {
|
|
return groups[2].length;
|
|
}
|
|
return 0;
|
|
}
|
|
function precisionRound(value, precision, base = 10) {
|
|
const exp = Math.pow(base, precision);
|
|
return Math.round(value * exp) / exp;
|
|
}
|