-1

How do I round off a money amount to two decimals using the arithmetic convention that

167,7451 is rounded to 167,75

12,1819784 is rounded to 12,18

Notice I want to do it arithmetically and be returned a float and not a string so simple formatting solutions are not what I'm searching for.

So far I found the following:

amount = 167.7451;
rounded = (amount.toFixed(2));
alert(rounded);

however the result of toFixed() is a string, so if I need to do more calculations I need to parse the string to a float again.

The .toPrecision method instead wants to know how many digits I need so to round the amount to two decimals I'd need:

amount = 167.7451;
alert(amount.toPrecision(5));

that's ridiculous because I'd need to first know how many digits I have before the decimals.

saimiris_devel
  • 667
  • 1
  • 6
  • 19
  • `167,7451 is rounded to 167,75` there's no decimal... – Bhojendra Rauniyar Jul 12 '16 at 07:21
  • `167,75` this is not even a valid number to begin with you have comma when you have hundreds not tens. or you mistype `,` instead of `.` ? – guradio Jul 12 '16 at 07:26
  • Answered here: http://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-in-javascript – janar2005 Jul 12 '16 at 07:33
  • @janar2005 there's like 20 answers in that page and the accepted one is wrong, that seems not very helping considering how common and simple this task should be. – saimiris_devel Jul 12 '16 at 07:53
  • @guradio I use the comma because currencies should be formatted with a comma after the units, then you'd of course use a dot in calculations. – saimiris_devel Jul 12 '16 at 07:53

1 Answers1

-1
167.7451 is rounded to <span class="result1"></span>
<br>By adding 10 result is: <span class="result2"></span>
<br>By adding rounded 0.254999 result is: <span class="result3"></span>

<script type="text/javascript">
    window.jQuery(document).ready(function($){
        function my_round(num) {
            return Math.round(num * 10 * 10) / 100;
        }

        var amount = 167.7451,
            amount1 = my_round(amount),
            amount2 = amount1 + 10,
            amount3 = amount2 + my_round(0.254999);


        window.jQuery('.result1').text( amount1 );
        window.jQuery('.result2').text( amount2 );
        window.jQuery('.result3').text( amount3 );
    });
</script>

Updated code should work.

janar2005
  • 24
  • 3