In this post we will see a set of functions that apply the ceil, round, floor and trunc functions on the nth digit in a float/decimal number.
The functionality is very simple and based on the built-in Math object. The logic is to multiply by 10 n times, apply the function from Math, and then divide by 10 also n times
module.exports = { /** * Performs ceil in the n decimal digit of num * @param num * @param n * @returns {number} */ dCeil: function(num, n) { let multiplyValue = Math.pow(10, n); console.log('dCeil', num, n, multiplyValue, Math.ceil(num / multiplyValue) * multiplyValue) return Math.ceil(num * multiplyValue) / multiplyValue; }, /** * Performs round in the n decimal digit of num * @param num * @param n * @returns {number} */ dRound: function(num, n) { let multiplyValue = Math.pow(10, n); return Math.round(num * multiplyValue) / multiplyValue; }, /** * Performs floor in the n decimal digit of num * @param num * @param n * @returns {number} */ dFloor: function(num, n) { let multiplyValue = Math.pow(10, n); return Math.floor(num * multiplyValue) / multiplyValue; }, /** * Performs trunc in the n decimal digit of num * @param num * @param n * @returns {number} */ dTrunc: function(num, n) { let multiplyValue = Math.pow(10, n); return Math.trunc(num * multiplyValue) / multiplyValue; } };
These functions have been included in v1.1.44 of the math.js npm package.
Leave a Reply