Formatting numbers in jquery

In this tutorial I’ll be showing you how you can format numbers which you input in textboxes.

 

Example

Here’s an example of unformatted numeric value:

image

Once you tab out of the textbox it becomes like this:

image

 

Requirements

 

What to do

First you need to include the files needed to format numeric values. You might want to order them in the same fashion as I made below:

<script type="text/javascript" src="jq.js">

</script> <script type="text/javascript" src="jhashtable.js">

</script>

<script type="text/javascript" src="jqnumformat.js">

</script>

 

Next is your form input. The number inside this textbox will be formatted to be more readable later on, just like in the example which I showed you earlier.

Decimal Number: <input type="text" name="decnum"

class="numeric" id="decnum"/>

Thirdly, we need to create the script that would actually perform the magic that we want to happen:

$('#decnum').blur(function(){

     $(this).parseNumber({format:"#,###.00", locale:"us"});
    $(this).formatNumber({format:"#,###.00", locale:"us"});
});

Remember to put the lines above inside the jquery document.ready() function. And remember to put the document.ready() function inside <script></script> tags.

You can actually tweak the script above to match your needs. If you need four decimal places then you can always add for zeros in there. You can also change the locale if you want. But the most commonly used is the us. So you might as well not want to change that.

 

Storing to database

Of course you’ll need to change it back to a format that is desirable for databases. To actually make use of the data later on.

$number = floatVal(str_replace(',', '', $_POST['decnum']));

The code above will strip all of the commas that has been appended by the jquery script.
So what’s the point then of having to format it then just storing the unformatted data into the database? Presentation my friends. It’s easier for the user to read numbers if its grouped using commas.

 

Conclusion

I just showed you a quick and simple way to format numeric inputs using jquery. And transform them back to the unformatted version if every you want to store it in a database.
I hope you enjoyed this tutorial, thanks for reading!

2 thoughts on “Formatting numbers in jquery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s