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

Setting a decimal place without another function? 1

Status
Not open for further replies.

JBruyet

IS-IT--Management
Joined
Apr 6, 2001
Messages
1,200
Location
US
Hey all,

It's been a couple of years since my JavaScript class and I have a question. I have JS for figuring out a dollar amount and I can't find a way to have the answer drop to two decimal places without running a second function (I'm looking through my old code but I don't have anything there to help me). Here's what I have:

function doMath() {
var GasPrice = eval(document.Stuff.GasPrice.value)
var Mpg = eval(document.Stuff.Mpg.value)
var TripMiles = eval(document.Stuff.TripMiles.value)
var DaysWeek = eval(document.Stuff.DaysWeek.value)
var GasCost = TripMiles / Mpg * GasPrice * DaysWeek
alert("You're paying $" + GasCost + " to drive back and forth to work each week")
}

I think it'd be easier for people using this "calculator" if the answer didn't go out for 15 decimal places. Is there a way to limit the GasCost value to two decimal places without building a second function? If not, is toFixed the only way to go?

Thanks,

Joe Brouillette
 
First, you don't need to eval() the form element values.

You can use the toFixed(NumberOfDecimalPlacesToDisplay) method to produce the results you want.

Code:
alert("You're paying $" + GasCost.toFixed(2) + " to drive back and forth to work each week");

Also, just for the sake of standards, I'd recommend using semicolons to terminate each line of code.

Lee
 
Thanks trollacious! I was putting the toFixed modifier in the wrong part of the code. I made your suggested change and it works great now. I think I'll even give you a star on this one 'cuz I look really good to the marketing department now.

And thanks for the suggestions as to the eval() and the semicolons.

Joe Brouillette
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top