Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Formatting decimals - which method?

Status
Not open for further replies.

DoctorGonzo

Programmer
Jan 23, 2004
48
0
0
GB
Hi guys,

I have the following code in the ONBLUR event of a field

FIELD3.value = FIELD2.value - FIELD1.value

this works fine, but if the sum is 13.20 - 12.50 the resulting answer is 0.6999999999999993.

What I want is to round up to 2 decimal places. it's currency you see.... I want the answer to be 0.70 (70p)

Can anyone help? I've seen so many conflicting methods... parse.float's and math.round.s etc...

Many thanks!

Gonzo


 
Hi,

check this:

Code:
<SCRIPT>
v1 = 13.20;
v2 = 12.50;
v3 = 11.20;


function format_number(f_nr)
{
    f_nr = ((Math.round((f_nr)*100))/100);
    
    str_nr = f_nr.toString();
    if (/\./.test(str_nr))
    {
        str_nr= str_nr+"00";
        
        return str_nr.replace(/(\.\d{2}).*/, '$1');
    }else
    {
        return str_nr +".00";
    };
}

alert(format_number(v1-v2))
alert(format_number(v1-v3))

</SCRIPT>

PM

___
____
 
If it is not those crazy bugs for ie, toFixed would be the most straightforward. It should do though for nn & ff.
[tt] FIELD3.value = (FIELD2.value - FIELD1.value).toFixed(2)
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top