0

How to calculate percentage and have up to two digits after the dot? Based on previous topic, I tried the following:

function calc(part, whole) {
    if (!whole)
        return 0.00;
    return parseFloat((100 * part/whole).toFixed(2));
}

But what I get:

console.log((100 * 11154/48291).toFixed(2)) // 23.10
console.log((100 * 11154/48291))  // 23.09747157855501

I want the final result to be 23.09 and not 23.10. Also I want to return a number and not a string. the toFixed() method rounds up and returns a string. How should I do it? Maybe lodash can help me somehow?

vesii
  • 2,760
  • 4
  • 25
  • 71
  • Does this answer your question? [Round to at most 2 decimal places (only if necessary)](https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary) – esqew May 18 '20 at 16:05
  • @esqew that's the one I tried to use. All of them round the result. – vesii May 18 '20 at 16:06

3 Answers3

0

You can do it this way:

Math.trunc((100 * part/whole) * 100)/100;
console.log(Math.trunc(100 * 11154/48291 *100)/100)  // 23.09

But if the number is negative Math.trunc will not round down.

More about Math.trunc

Levizar
  • 75
  • 1
  • 8
0

You can try this

function calc(part, whole) {
    if (!whole)
        return 0.00;

    const valueStr = parseFloat((100 * part/whole)).toString();
    const dot = valueStr.indexOf('.');

    if(dot !== -1) {
      return Number(valueStr.slice(0, dot + 3));
    } else {
      return Number(valueStr);
    }
}

//testing
console.log(calc(23,45));
console.log(calc(83,23))
console.log(calc(12,12))
console.log(calc(14,76))
alexortizl
  • 2,125
  • 1
  • 12
  • 27
0

you can use that function to do the trick

function trunc_to_precision(number, precision) {
  numberAsStr = number.toString();
  if (!numberAsStr.includes('.')) {
    return number;
  }

  let [entier, decimal] = numberAsStr.split('.');

  return parseFloat(entier + '.' + decimal.substring(0,precision));
}

let x = trunc_to_precision(23.09747157855501, 2); // 23.09 as float
Wonkledge
  • 1,732
  • 7
  • 16