JQuery round off money / currency to 2 decimals
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.
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>
更新的代码应该可以工
链接地址: http://www.djcxy.com/p/21376.html