4
<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.

0

4 Answers 4

6

You're calling toFixed in the wrong place:

$(this).val( (Math.round(amt*100)/100).toFixed(2) ); 
Sign up to request clarification or add additional context in comments.

3 Comments

this is done using jQuery. can this be done using only Javascript only?
@shiva The jQuery isn't too far from vanilla JavaScript. Rather than $(this).val() you would simply assign the results to this.value. What browser-support do you need? While more modern browsers support addEventListener, you'd have to fallback to attachEvent when it's present, and further back to modifying element members directly when neither are present.
I think (Math.round(amt*100)/100).toFixed(2) can be simplified to amt.toFixed(2).
3

It is more simple than you think:

amt.toFixed(2) 

Comments

2

This can be done using Javascript as follows:

this.value = (Math.round(amt*100)/100).toFixed(2); 

If it is a single text input:

document.getElementById("txtNum").value = (Math.round(amt*100)/100).toFixed(2); 

4 Comments

It looks like the code is not working as expected. There is an extra ) which produces a SyntaxError. The (amt*100)/100 part is the same as amt.
@cbliard : The code "Math.round((amt*100)/100).toFixed(2)" is picked up from the question. Hence, I din't check what it does.
Note quite: the original code is (Math.round(amt*100)/100).toFixed(2)
@cbliard : Noted and incorporated.
0

The sample code below works, too.

ProperRoundCircle = function(num, decimal){ return Math.round(parseFloat(Number) * Math.pow(10, decimal)) / Math.pow(10, decimal); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.