JQuery round off money / currency to 2 decimals

有些话、适合烂在心里 提交于 2019-12-25 18:31:39

问题


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.


回答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.



来源:https://stackoverflow.com/questions/38322372/jquery-round-off-money-currency-to-2-decimals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!