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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Changing String to Number + Setting Decimal Points

Status
Not open for further replies.

Dudds

Technical User
Sep 28, 2004
6
US
Is there a simple way to force a numerical '+' rather than a string '+' in a function? I'm a beginner with JavaScript but cannot find instruction on how to add two values together in a function as numbers - currently they're being added as strings (one value appended on the end of another).

Also, is there a way to set decimal places on the output of such a calculation?

Many thanks
Graham Duddridge
 
the parseInt() function will make a string containing "1" a number 1. Like this:

[tt]var the_total = parseInt("1") + parseInt("2");[/tt]

If your value is a "float", you'll need to parseFloat. Like this:

[tt]var the_total = parseFloat("1.234") + parseFloat("2.345");[/tt]


*cLFlaVA
----------------------------
Lois: "Peter, you're drunk!"
Peter: "I'm not drunk, I'm just exhausted from stayin' up all night drinking!
 
Superb - many thanks for your help. Do you know how to set the float to two decimal places, e.g. 12.34?
 
There are built-in JS functions for this, however many people have problems getting these to work for some reason.

This solution works for me:
Code:
var one = 3.246;
var two = 2.112;
var tot = Math.round((100*(one + two)))/100);

*cLFlaVA
----------------------------
Lois: "Peter, you're drunk!"
Peter: "I'm not drunk, I'm just exhausted from stayin' up all night drinking!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top