ToFixed () Simple use / explanation in a textbox
I have avoided asking this question here, as I know many in the past. Over the past few days, I've spent some time trying to find a solution / figure out how the toFixed () method works. I have read many questions on this site and tutorials about others, but I still don't get it.
I have several text boxes with a class, .entry. It is assumed that there will be a dollar amount here. When people type the following (examples):
1.2
5
6.35
8.
I need them to change to:
1.20
5.00
6.35
8.00
In other words, add trailing zeros. I know this is achieved with the toFixed () method, but I'm completely at a loss. I cannot get it to work.
I have a script I have found that it sums all text fields in a DIV elsewhere in the page and I notice that it uses the toFixed () method:
$("#total").html(sum.toFixed(2).replace(/(^\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1,'));
}
I tried using the same code here to get zeros to appear in the textbox:
$('.entry').keyup(function(){
var str = this.value.replace(/(^\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1');
if (str!=this.value) this.value = str;
});
This does not work.
I'm new to JQuery and Javascript, so I realize that I probably missed something obvious. Most of the tutorials I've read set a variable in code and then use "document.write" to display the variable with the correct number of zeros:
Example:
document.write( 1.1.toFixed(2) + '<br>' );
But that's not what I'm looking for. I need it to appear in a textbox.
Thanks in advance!
source to share
A few things:
- Use
change
event insteadkeyup
. If you usekeyup
, the text wil changes every time the user tries to enter something that annoys the user. - Consider using a step
input
type .number
0.1
With that in mind, I would do something like this:
$('.entry').change(function(){
// parse the typed value as a floating point number
var num = parseFloat(this.value);
// ensure there are two decimal places
this.value = num.toFixed(2);
});
Note that if the user enters something with more than two decimal places, the value will be rounded.
Example: http://jsfiddle.net/jndt1e02/
source to share