It's odd that I've recently known how to do decimal format in javascript. Because, in the new change requests of our projects, I need to do on-the-fly calculation total amount once users change quantity. It seems so simple to use the built-in function of javascript but value parsing via javascript it a bit touch.

Here is the example.

view plain print about
1<!---
2    Please assume that "56.50" is in document.myForm.txtPrice.value
3    and quantity is 5.
4--->

It's the wrong using of fetching decimal value in JS.

view plain print about
1var getPrice = parseInt(document.myForm.txtPrice.value);

It's the wrong using of fetching decimal value in JS.

view plain print about
1var getPrice = parseFloat(document.myForm.txtPrice.value);

This one is calculate amount of item.

view plain print about
1var getAmount = getPrice * qty

So, I need to assign getAmount result into input text. In CF, we can use NumberFormat which is very simple. If I assign like that in Javascript, decimal value will be disappeared in input box for sure.

view plain print about
1document.myForm.txtAmount.value = getAmount;

At that time, I need to use "toFixed" in javascript for formatting decimal format.

Usage

number.toFixed(x)

x = Optional. The number of digits after the decimal point. Default is 0 (no digits after the decimal point)

So, here is coding how to assign decimal value into input text with javascript.

view plain print about
1document.myForm.txtAmount.value = getAmount.toFixed(2);

I think most of people already know about this "toFixed" function in javascript but for me, I know this function recently.

Best credit : http://www.w3schools.com/jsref/jsref_tofixed.asp