473,883 Members | 1,703 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need help with rounding on a calculation

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.getEle mentById('perGa llon');
var b = document.getEle mentById('tripD istance');
var c = document.getEle mentById('mpg') ;
var d = document.getEle mentById('tripC ost');
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" />&nbsp;&nbsp;
<br />
Trip distance in Miles: <input type="text" id="tripDistanc e"
name="tripDista nce"
value="300" /><br />
MPG for your vehicle: <input type="text" id="mpg" name="mpg" value="18"
/><br/><br/>
<input type="button" value="Calculat e" onclick="calcTr ipCost();" /<br
/>
Gas cost for your trip:&nbsp; $ <input type="text" id="tripCost" />

</body>

Thank You, Larry

Jun 27 '08 #1
9 1524
On Apr 22, 8:06 pm, "Verizon News Server" <anonymous@no_s pam.info>
wrote:
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.getEle mentById('perGa llon');
var b = document.getEle mentById('tripD istance');
var c = document.getEle mentById('mpg') ;
var d = document.getEle mentById('tripC ost');
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" />&nbsp;&nbsp;
<br />
Trip distance in Miles: <input type="text" id="tripDistanc e"
name="tripDista nce"
value="300" /><br />
MPG for your vehicle: <input type="text" id="mpg" name="mpg" value="18"
/><br/><br/>
<input type="button" value="Calculat e" onclick="calcTr ipCost();" /<br
/>
Gas cost for your trip:&nbsp; $ <input type="text" id="tripCost" />

</body>

Thank You, Larry
Math.round(x * 100)/100

the following alerts 64.17
alert(Math.roun d(64.166666666 * 100)/100);
Jun 27 '08 #2
On Apr 23, 11:06 am, "Verizon News Server" <anonymous@no_s pam.info>
wrote:
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.
The FAQ is good for that:

4.6 How do I convert a Number into a String with exactly 2 decimal
places?
<URL: http://www.jibbering.com/faq/#FAQ4_6 >

Here is what I have so far. I tried to
use the toFixed(2), but couldn't figure out where to put it.
Don't, it's broken in some implementations (see link above).
>
<head>
<title></title>
<script type="text/javascript">
function calcTripCost(){
var a = document.getEle mentById('perGa llon');
var b = document.getEle mentById('tripD istance');
var c = document.getEle mentById('mpg') ;
var d = document.getEle mentById('tripC ost');
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;
You should test values before using them for arithmetic operations to
make sure they are numbers within a suitable range. At the very
least, check that mpg is not zero.
--
Rob
Jun 27 '08 #3
Thanks, Doug.

Admittedly, I am inept with javascript and in over my head on this simple
little project. I don't know how to integrate the math.round into my
script. Could you or someone help me place it where it needs to be?

Any helps is very appreciated. Thanks in advance.

Larry
"Doug Gunnoe" <do********@gma il.comwrote in message
news:89******** *************** ***********@i76 g2000hsf.google groups.com...
On Apr 22, 8:06 pm, "Verizon News Server" <anonymous@no_s pam.info>
wrote:
>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.getEle mentById('perGa llon');
var b = document.getEle mentById('tripD istance');
var c = document.getEle mentById('mpg') ;
var d = document.getEle mentById('tripC ost');
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="perGallo n"
value="3.85" />&nbsp;&nbsp;
<br />
Trip distance in Miles: <input type="text" id="tripDistanc e"
name="tripDist ance"
value="300" /><br />
MPG for your vehicle: <input type="text" id="mpg" name="mpg"
value="18"
/><br/><br/>
<input type="button" value="Calculat e" onclick="calcTr ipCost();" />
<br
/>
Gas cost for your trip:&nbsp; $ <input type="text" id="tripCost" />

</body>

Thank You, Larry

Math.round(x * 100)/100

the following alerts 64.17
alert(Math.roun d(64.166666666 * 100)/100);


Jun 27 '08 #4
On Apr 23, 9:33 am, "Larrythedesign er" <anonymous@no_s pam.infowrote:
Thanks, Doug.

Admittedly, I am inept with javascript and in over my head on this simple
little project. I don't know how to integrate the math.round into my
script. Could you or someone help me place it where it needs to be?

Any helps is very appreciated. Thanks in advance.

Larry
Sure. And you might want to check out what Rob was saying about
checking the values, etc. Like he says, you don't want to divide by
zero. Also, JavaScript can be tricky when doing stuff like this
because of converting values between strings and numbers. But I see
you were using the parseFloat function so you seem to be headed in the
right direction in that regard.

Anyway, to your question, you would use it something like this

var tripcost = tripDistance/mpg*perGallon;
d.value = Math.round(trip cost * 100)/100;



Jun 27 '08 #5
Thank You Doug!

I appreciate your help. That did the trick. I am still learning and this
helped me understand some of what I learned.

Thanks, Larry
"Doug Gunnoe" <do********@gma il.comwrote in message
news:8d******** *************** ***********@34g 2000hsh.googleg roups.com...
On Apr 23, 9:33 am, "Larrythedesign er" <anonymous@no_s pam.infowrote:
>Thanks, Doug.

Admittedly, I am inept with javascript and in over my head on this simple
little project. I don't know how to integrate the math.round into my
script. Could you or someone help me place it where it needs to be?

Any helps is very appreciated. Thanks in advance.

Larry

Sure. And you might want to check out what Rob was saying about
checking the values, etc. Like he says, you don't want to divide by
zero. Also, JavaScript can be tricky when doing stuff like this
because of converting values between strings and numbers. But I see
you were using the parseFloat function so you seem to be headed in the
right direction in that regard.

Anyway, to your question, you would use it something like this

var tripcost = tripDistance/mpg*perGallon;
d.value = Math.round(trip cost * 100)/100;



Jun 27 '08 #6
In comp.lang.javas cript message <898cd037-3c3d-4346-9d66-5725a1f22a31@i7
6g2000hsf.googl egroups.com>, Tue, 22 Apr 2008 20:18:20, Doug Gunnoe
<do********@gma il.composted:
>
Math.round(x * 100)/100

the following alerts 64.17
alert(Math.rou nd(64.166666666 * 100)/100);
Those who fail to read the FAQ before posting commonly demonstrate
ineptness.

Evidently you have not considered the difference between rounding to a
multiple 0f 0.01 and rounding to two decimals. Currency outputs should
be rounded to the nearest penny or pound (or foreign equivalents), not
to the nearest florin (unless large, of course).

--
(c) John Stockton, nr London, UK. ?@merlyn.demon. co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demo n.co.uk/- FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "" (SonOfRFC1036)
Jun 27 '08 #7
In comp.lang.javas cript message <8d195c89-548d-4486-8ef5-c04992bb57c4@34
g2000hsh.google groups.com>, Wed, 23 Apr 2008 12:30:31, Doug Gunnoe
<do********@gma il.composted:
But I see
you were using the parseFloat function so you seem to be headed in the
right direction in that regard.
Function parseFloat is not needed in that code. FAQ 4.21.

--
(c) John Stockton, nr London, UK. ?@merlyn.demon. co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demo n.co.uk/- FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "" (SonOfRFC1036)
Jun 27 '08 #8
In comp.lang.javas cript message <653f34c9-01a2-4535-b296-7e41d21d52d1@e3
9g2000hsf.googl egroups.com>, Wed, 23 Apr 2008 19:11:02, Doug Gunnoe
<do********@gma il.composted:
>By the way, I will never, ever, ever, ever, never read the shitty FAQ.
Never. Never, ever, never.
Then, if you continue to post here what you naively think are answers,
you will continue to demonstrate your childish obstinacy, and it will
continue to be remarked upon.

Your mere ignorance and lack of understanding are not necessarily to be
ashamed of, provided that obvious steps to remedy them are promptly
taken.

--
(c) John Stockton, nr London UK. ??*@merlyn.demo n.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demo n.co.uk/- FAQish topics, acronyms, & links.
Check boilerplate spelling -- error is a public sign of incompetence.
Never fully trust an article from a poster who gives no full real name.
Jun 27 '08 #9
On Apr 27, 7:52 am, Dr J R Stockton <j...@merlyn.de mon.co.ukwrote:
Agreed. But you gave an answer inadequate for the application.
It was perfectly 'adequate' for the application, considering the
application.
You are either one of the subtler trolls,
I've been called worse
or too inexperienced to be of any real use.
Use for whom? For someone as smart as yourself, with such deep, low
level technical knowledge of JavaScript, I doubt that I would be of
any benefit. That being the case, please feel free to ignore all my
future posts.
A pointless remark. Those who, in that case, use parseFloat have only
made the obvious first step in their understanding.
Which was the only point I was making. If you ever get around to
reading the OP, he states several times that he is a n00b to
JavaScript.
You, it seems, choose to go no further.
I had no need to go any further. Like me, you didn't notice it the
first time you browsed through it either. It was only after I
challenged your asshatery that you went back and looked for additional
ways to criticize my answer. (Oh, and you know it's true lol.)
Giving unsatisfactory answers when you could have left the matter to
those more capable is not nice; you get here what you therefore deserve.
If you will notice, Mr. Stockton, those more capable have still not
answered the OP's question.

Evertjan wrote:
Don't take it hard, Doug, we are here to enjoy,
and Javascript, like chess, gives intellectual enjoyment.
It's cool, Evertjan. I don't mind being wrong. If I did my life would
be total misery.

Jun 27 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
5124
by: Lynn N. | last post by:
I have a report showing Rate, Hours and Total Pay (which is Rate*Hours) for several workers. I want to sum the Total Pay and get a CORRECT figure. This seems like it should be such a simple task. But there seems to be rounding issues in Access 2000 that I can't figure out. It seems that, even though the report is displaying Total Pay as currency rounded off to two decimal places, the report is actually using more than two decimal places...
2
1820
by: Tony Williams | last post by:
I have a form with a tabcontrol which has a number of pages. I want to check the value of a calculated control on one page with a calculated control on another page. The calculated control (txtTotNbrClients) on page 3 is the sum of these controls on that page ( + + + + + + + ) The calculated control on page 4 (txtClientsTot) is the sum of these controls on that page ( + + + +
5
2750
by: Cygnus | last post by:
Sorry in advance for the lack of formatting in this posting. Data: (column headers) Net Sales | Royalty Rate | Total Royalty (data) 4.31 | 50.00% | 2.15 19.35 | 50.00% | 9.68
15
3112
by: Chris | last post by:
>>from math import * 0.0 1.2246063538223773e-016 -2.4492127076447545e-016 1.0 -1.0 1.0 The cosine function works fine, but I'm getting weird answers for sine. Is this a bug? Am I doing something wrong?
52
1565
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How do I convert a Number into a String with exactly 2 decimal places? ----------------------------------------------------------------------- When formatting money for example, to format 6.57634 to 6.58, 6.5 to 6.50, and 6 to 6.00? Rounding of x.xx5 is uncertain, as such numbers are not represented exactly.
19
3624
by: VK | last post by:
http://groups.google.com/group/comp.lang.javascript/browse_frm/thread/ b495b4898808fde0> is more than one month old - this may pose problem for posting over some news servers. This is why I'm starting a new one] I'd still like to finish this rounding mess. As a startup lemma we can take that VK is the worst programmer of all times and places: let's move from here forward please. The usability of any program depends on exact behavior...
30
29768
by: bdsatish | last post by:
The built-in function round( ) will always "round up", that is 1.5 is rounded to 2.0 and 2.5 is rounded to 3.0. If I want to round to the nearest even, that is my_round(1.5) = 2 # As expected my_round(2.5) = 2 # Not 3, which is an odd num I'm interested in rounding numbers of the form "x.5" depending upon whether x is odd or even. Any idea about how to implement it ?
18
1445
by: Philluminati | last post by:
I am writing a poker game which needs to work with cash. I am aware that there are problems with floats that make them unsuitable for storing money values. On top of this I may be expected to do operations such as £10.52 / 3. Which data type should I use instead? Is there an Industry standard one? Further to this, is anyone away of legally what the obligations would be when the outcome is 3.566666667? does the customer get 56 or 57p?...
8
2789
by: jac130 | last post by:
I need to create a calculator using combo boxes/procedures/functions etc... and some other stuff. most of it works properly, but, i need to create a user defined function that checks if both input numbers of the calculation are in fact numbers (isnumeric). the function must check both numbers, display a message box and return a value. but it crashes every time i test it - like putting in a letter instead of a number. any help would be great,...
0
9938
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9791
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11140
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10847
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9572
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7971
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7125
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5991
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3232
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.