Home > database >  Limit and round number
Limit and round number

Time:06-15

I want to limit the number to max 5 digits by rounding the decimal. If we have less than 5 digits the number should stay untouched. Could anyone help me to write that function?

function limitAndRoundNumber(number) {
 ...
}

Exemplary inputs and outputs:

limitAndRoundNumber(1.234) should return 1.234 (unchanged because number has less than 5 digits) 
limitAndRoundNumber(1.234567) should return 1.2346
limitAndRoundNumber(12.34567) should return 12.346
limitAndRoundNumber(123.4567) should return 123.46
limitAndRoundNumber(1234.567) should return 1234.6
limitAndRoundNumber(12345) should return 12345

Input number can be grater than 0 and less than 100000

CodePudding user response:

One solution is to convert the number to a string and use String.slice(0,requiredLength) to adjust the length before returning a number version of the string.

The length would depend on whether the number contained a decimal separator, which could be determined by a conditional within the function.

Working snippet:

function limitAndRoundNumber(number) {
const length = (number.toString().indexOf('.')) ? 6 : 5;

return parseFloat(number.toString().slice(0,length));
}

console.log(limitAndRoundNumber(1.234567));
console.log(limitAndRoundNumber(12.34567));
console.log(limitAndRoundNumber(123.4567));
console.log(limitAndRoundNumber(1234.567));
console.log(limitAndRoundNumber(12345));
console.log(limitAndRoundNumber(12));
console.log(limitAndRoundNumber(12.3));

The function could be modified to allow for any length, by including a length argument and referencing it in the ternary operator test for the decimal separator:

length = (number.toString().indexOf('.')) ? length 1 : length;

CodePudding user response:

I tend to use the following to cut a number to a set number of decimals

Math.round(number * multiplier) / multiplier

Where 'multiplier' is 10 to the power of the number of decimals. Now you only need to figure out what the multiplier needs to be, and you can do that by rounding to a whole value and getting the string length of the number. So something like:

function limitAndRoundNumber(number) {
  const wholeDigits = Math.round(number).toString().length;
  const power = wholeDigits <= 5 ? 5 - wholeDigits : 0;
  const multiplier = 10**(power);

  return Math.round(number * multiplier) / multiplier;
}

console.log(limitAndRoundNumber(1.23));
console.log(limitAndRoundNumber(1.234567));
console.log(limitAndRoundNumber(12.34567));
console.log(limitAndRoundNumber(123.4567));
console.log(limitAndRoundNumber(1234.567));
console.log(limitAndRoundNumber(12345));
console.log(limitAndRoundNumber(123456));

  • Related