0

How to round 0.023 to 0.03 in JavaScript

This is what i tried. but it gives 0.024 var abc = 0.023, factor = 0.003; abc = Math.round(abc / factor) * factor; console.log(abc);

how should i get 0.03

Emilis
  • 152
  • 1
  • 4
  • 21
  • 1
    What is the logic behind that rounding? Do you want to round up to the next tenth? – str May 19 '19 at 17:46
  • Yes. I am calculating commisions from payments – Emilis May 19 '19 at 17:48
  • 1
    Possible duplicate of [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) – Tibrogargan May 19 '19 at 17:51
  • See the duplicate question and use `Math.ceil` instead of `Math.round`. – str May 19 '19 at 17:52
  • I think perhaps what you want is `Math.round(abc * (1 + (factor * 100)) * 100)/100`, but your question is very unclear. You need to explain that you're doing two things: 1) Modifying the price by some commission factor (assumption: a percentage) and then rounding the resulting value to two decimal places – Tibrogargan May 19 '19 at 17:59

2 Answers2

1

I think you mean rounding float number up. I found solution here: How to round up a number in Javascript?

First parameter is number that you want to round. Second parameter is number (integer) of numbers after point that you want to get.

function roundUp(num, precision) {
   precision = Math.pow(10, precision)
   return Math.ceil(num * precision) / precision
 }
  
 result = roundUp(0.023, 2)
 console.log(result)
Dolidod Teethtard
  • 553
  • 1
  • 7
  • 22
0
abc = Math.ceil((abc/factor)*factor * 100) / 100;

ceil rounds up a number to the integer value.

Tibrogargan
  • 4,508
  • 3
  • 19
  • 38
Simon Nitzsche
  • 723
  • 6
  • 13