3

I need to write a function that will ALWAYS round up, but will either round up to 0, 1 or 2 decimal places, depending on if the function is passed a 0, 1 or 2.

Examples...

Round to 0 decimal places: 13.4178 = 14

Round to 1 decimal place: 13.4178 = 13.5

Round to 2 decimal places: 13.4178 = 13.42

I've found Math.ceil but this only rounds up to a whole integer and to fixed() will round up or down, not just up. Is there a way to round up in the way I've described above?

Janey
  • 1,260
  • 3
  • 17
  • 39
  • You could also take a longer look at `Math.ceil` documentation on the MDN... – Serge K. Aug 21 '17 at 09:27
  • 1
    `(num, signs) => Math.ceil(num * 10**signs)/10**signs;` – raina77ow Aug 21 '17 at 09:27
  • 1
    Write some code that combines `Math.ceil()` and `toFixed()` and if that doesn't work as you expect, put your code in your question. Then others can help you, instead of just writing your code for you. – Kokodoko Aug 21 '17 at 09:28
  • if you tried reading documentation, you could've come across the MDN documentation, that may have a function or two to help in your quest - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil#Decimal_adjustment – Jaromanda X Aug 21 '17 at 09:29
  • 1
    I do not think this is homework. Just browse through the other contributions of this user – Tobias Gassmann Aug 21 '17 at 09:37
  • @Script47 it's not homework, I'm just rubbish at math! Thanks for the help everyone the working answer is below. – Janey Aug 21 '17 at 10:04
  • This question is indeed a duplicate of "How to round up in Javascript", but it is *not* a duplicate of "Round to at most 2 decimal places (only if necessary)" – Tobias Gassmann Aug 21 '17 at 10:19
  • @TobiasGassmann yep that's correct – Janey Aug 21 '17 at 10:47

3 Answers3

10

You could use a factor for multiplication with ten and the power of the wanted decimal count and then round it and adjust the dot.

function up(v, n) {
    return Math.ceil(v * Math.pow(10, n)) / Math.pow(10, n);
}

console.log(up(13.4178, 0));
console.log(up(13.4178, 1));
console.log(up(13.4178, 2));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Just multiply, round up and divide by a factor of 10^dec.

function roundUp( num, dec ) {
  // raise by dec, default to 0 decimals at the and.
  const d = Math.pow( 10, ( dec || 0 ) );
  // Multiply, round up and divide back so your decimals remain the same
  return Math.ceil( num * d ) / d;
}

console.log( roundUp( 1.2345 ) );
console.log( roundUp( 1.2345, 1 ) );
console.log( roundUp( 1.2345, 2 ) );
console.log( roundUp( 1.2345, 3 ) );
lumio
  • 7,428
  • 4
  • 40
  • 56
0

Use auxiliary multiplication and division:

function MyCeil(number, digits) {
  var factor = Math.pow(10, digits);
  return Math.ceil(number*factor) / factor;
}
Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Alexander
  • 4,420
  • 7
  • 27
  • 42