V
Verizon News Server
Hi, I am a newbie with Javascript. I am trying to build a simple form that
calculates the cost of gasoline for a trip.
It simply divides the trip distance by the mpg and multiplies that by the
current per gallon price.
It works, fine except I want to round the number to two decimals ( 64.16,
not 64.166666666)
Any help is greatly appreciated. Here is what I have so far. I tried to
use the toFixed(2), but couldn't figure out where to put it.
<head>
<title></title>
<script type="text/javascript">
function calcTripCost(){
var a = document.getElementById('perGallon');
var b = document.getElementById('tripDistance');
var c = document.getElementById('mpg');
var d = document.getElementById('tripCost');
var perGallon = parseFloat (a.value);
var tripDistance = parseFloat (b.value);
var mpg = parseFloat (c.value);
var tripCost = parseFloat (d.value);
d.value = tripDistance/mpg*perGallon;
}
</script>
</head>
<body>
Price per gallon of gas: <input type="text" id="perGallon"
name="perGallon"
value="3.85" />
<br />
Trip distance in Miles: <input type="text" id="tripDistance"
name="tripDistance"
value="300" /><br />
MPG for your vehicle: <input type="text" id="mpg" name="mpg" value="18"
/><br/><br/>
<input type="button" value="Calculate" onclick="calcTripCost();" /> <br
/>
Gas cost for your trip: $ <input type="text" id="tripCost" />
</body>
Thank You, Larry
calculates the cost of gasoline for a trip.
It simply divides the trip distance by the mpg and multiplies that by the
current per gallon price.
It works, fine except I want to round the number to two decimals ( 64.16,
not 64.166666666)
Any help is greatly appreciated. Here is what I have so far. I tried to
use the toFixed(2), but couldn't figure out where to put it.
<head>
<title></title>
<script type="text/javascript">
function calcTripCost(){
var a = document.getElementById('perGallon');
var b = document.getElementById('tripDistance');
var c = document.getElementById('mpg');
var d = document.getElementById('tripCost');
var perGallon = parseFloat (a.value);
var tripDistance = parseFloat (b.value);
var mpg = parseFloat (c.value);
var tripCost = parseFloat (d.value);
d.value = tripDistance/mpg*perGallon;
}
</script>
</head>
<body>
Price per gallon of gas: <input type="text" id="perGallon"
name="perGallon"
value="3.85" />
<br />
Trip distance in Miles: <input type="text" id="tripDistance"
name="tripDistance"
value="300" /><br />
MPG for your vehicle: <input type="text" id="mpg" name="mpg" value="18"
/><br/><br/>
<input type="button" value="Calculate" onclick="calcTripCost();" /> <br
/>
Gas cost for your trip: $ <input type="text" id="tripCost" />
</body>
Thank You, Larry