Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript rounding to two decimal places

Tags:

javascript

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Round to 2 Decimal Places</title>
    <script type="text/javascript"
    src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
    </script>
    <script type="text/javascript">
        $(function() {
            $('input#txtNum').blur(function() {
                var amt = parseFloat(this.value);
                //$(this).val('$' + amt.toFixed(2));
                $(this).val((Math.round(amt*100))/100).toFixed(2);
            });

        });
    </script>
</head>
<body>
    Type a decimal number in the TextBox and hit Tab
    <br />
    <input id="txtNum" type="text" />
</body>
</html>

when i am entering value as 100.2569.The result shows 100.26 but when i am entering 56.999 its showing 57 instead of 57.00 or if i am giving value without decimal its showing without decimals without two appending two zeroes after decimal.

like image 776
shiva Avatar asked Dec 20 '22 11:12

shiva


2 Answers

You're calling toFixed in the wrong place:

$(this).val( (Math.round(amt*100)/100).toFixed(2) );
like image 189
Sampson Avatar answered Jan 02 '23 19:01

Sampson


It is more simple than you think:

amt.toFixed(2)
like image 31
Mohamed Mansour Avatar answered Jan 02 '23 17:01

Mohamed Mansour