467,910 Members | 1,565 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,910 developers. It's quick & easy.

scrip drops a penny when amount ends with .d0

I call a function that takes the unit price and quantity ordered to
create an amount...it looks something like this.

function calculateCost()
{
quantity=document.RFO.quantity.value;
unitPrice=document.RFO.unitPrice.value;
total=0;
if(isPositiveInteger(quantity))
{
quantity=parseFloat(quantity)
{
total=quantity * unitPrice;
}
}
document.RFO.total.value=format(total)
}

if a person enters a unit price that ends with .10, .20, .30, ..., .90,
my code drops a penny off the total? However if the price ends with .1,
..2, .3, ..., .9, my code works fine.
Seems it has a problem calculating prices ending with 0 unless it's .00

May 10 '06 #1
  • viewed: 2006
Share:
35 Replies
VK

ey****@ncsa.uiuc.edu wrote:
if a person enters a unit price that ends with .10, .20, .30, ..., .90,
my code drops a penny off the total? However if the price ends with .1,
.2, .3, ..., .9, my code works fine.
Seems it has a problem calculating prices ending with 0 unless it's .00


<http://www.jibbering.com/faq/#FAQ4_6>

May 10 '06 #2
Why would I need to convert a number into a string?

May 10 '06 #3
ey****@ncsa.uiuc.edu wrote:
Why would I need to convert a number into a string?


Why do you want to know?

Quote, please!

May 10 '06 #4
You told me to go to http://www.jibbering.com/faq/#FAQ4_6
this was the answer to my question....

http://www.jibbering.com/faq/#FAQ4_6 explains how to convert a number
into a string

May 10 '06 #5
VK

ey****@ncsa.uiuc.edu wrote:
Why would I need to convert a number into a string?


Because you don't want to have your penni lost. What was a question,
was it? <11**********************@e56g2000cwe.googlegroups .com>

May 10 '06 #6
ey****@ncsa.uiuc.edu wrote:
I call a function that takes the unit price and
quantity ordered to create an amount...it looks
something like this.

function calculateCost()
{
quantity=document.RFO.quantity.value;
unitPrice=document.RFO.unitPrice.value;
total=0;
The variables - quantity -, - unitPrice - and - total - should be
declared local to the function using the - var - keyword whenever there
is no good reason for them being global (and there doesn't appear to be
any reason for that).
if(isPositiveInteger(quantity))
{
quantity=parseFloat(quantity)
Why - parseFloat -? Surly a quantity has got to be an integer (and
particularly if - isPositiveInteger - does what its name suggests), so
why not - parseInt - and if you are verifying that the string contains a
representation of a positive integer why not let the type conversion
implicit in multiplication do that job.
{ ^ total=quantity * unitPrice;
} ^

What are these opening and closing braces doing here? They form a Block
statement, but there is no reason for a Block statement appearing here.
}
document.RFO.total.value=format(total)
}

if a person enters a unit price that ends with .10,
.20, .30, ..., .90, my code drops a penny off the
total? However if the price ends with .1, .2, .3,
..., .9, my code works fine. Seems it has a problem
calculating prices ending with 0 unless it's
.00


There is nothing in this code that would suggest the phenomenon you
describe. A quick test of the javascript operations you are using finds
no evidence of differing results using strings with trailing zeros and
the same strings with the trailing zeros stripped off:-

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
</head>
<body>
<pre>
<script type="text/javascript">

var l = [
'1.00','1.10','1.20','1.30','1.40','1.50','1.60',' 1.70','1.80','1.90',
'2.00','2.10','2.20','2.30','2.40','2.50','2.60',' 2.70','2.80','2.90',
'3.00','3.10','3.20','3.30','3.40','3.50','3.60',' 3.70','3.80','3.90',
'4.00','4.10','4.20','4.30','4.40','4.50','4.60',' 4.70','4.80','4.90',
'5.00','5.10','5.20','5.30','5.40','5.50','5.60',' 5.70','5.80','5.90',
'6.00','6.10','6.20','6.30','6.40','6.50','6.60',' 6.70','6.80','6.90',
'7.00','7.10','7.20','7.30','7.40','7.50','7.60',' 7.70','7.80','7.90',
'8.00','8.10','8.20','8.30','8.40','8.50','8.60',' 8.70','8.80','8.90',
'9.00','9.10','9.20','9.30','9.40','9.50','9.60',' 9.70','9.80','9.90'
];
var q = [
'1','2','3','4','5','6','7','8','9'
];

function isPositiveInteger(){
return true;
}

function calculateCost2(x, y){
quantity = q[y];
unitPrice = l[x];
total=0;
var unitPrice2, total2;
if(isPositiveInteger(quantity)){
quantity = parseFloat(quantity)
{
total = quantity * unitPrice;
unitPrice2 = unitPrice.substring(0, (unitPrice.length - 1));
total2 = quantity * unitPrice2;
}
}
return (quantity+' * '+unitPrice+' = '+total+'\n'+quantity+' * '+
unitPrice2+' = '+total2+'\t\t'+
((total != total2)?'********** Differ **********':''));
}

for(var c = 0;c < q.length;++c){
for(var d = 0;d < l.length;++d){
document.write(calculateCost2(d, c)+'\n\n')
}
}

</script>
</per>
</body>
</html>

With no evidence of the phenomena it cannot be attributed. You will have
to create an example that actually shows this in action. It would be a
good idea to mention the browser you are using in case this is an
implementation specific bug (I used IE and Mozilla for testing the above
code).

(Incidentally, although the FAQ reference VK posted is relevant to the
issues of money calculations and number to formatted string
transformations, it cannot account for the symptoms you describe. VK
should generally be ignored, he does not know javascript at all and as a
result he cannot see what would be expected from executing javascript
code, and so is incapable of attributing effects to causes except by
(inevitably often wrong) guess-work.)

Richard.
May 10 '06 #7
JRS: In article <11**********************@e56g2000cwe.googlegroups .com>
, dated Tue, 9 May 2006 08:32:06 remote, seen in
news:comp.lang.javascript, ey****@ncsa.uiuc.edu posted :
I call a function that takes the unit price and quantity ordered to
create an amount...it looks something like this.

function calculateCost()
{
quantity=document.RFO.quantity.value;
unitPrice=document.RFO.unitPrice.value;
total=0;
if(isPositiveInteger(quantity))
{
quantity=parseFloat(quantity)
{
total=quantity * unitPrice;
}
}
document.RFO.total.value=format(total)
}

if a person enters a unit price that ends with .10, .20, .30, ..., .90,
my code drops a penny off the total? However if the price ends with .1,
.2, .3, ..., .9, my code works fine.
Seems it has a problem calculating prices ending with 0 unless it's .00


Your code lacks isPositiveInteger and format, so cannot be tested by me.

Your first move should be to omit use of format, since you need to know
whether there is an error up to that stage; or to try alert(total)
before that. H'mmm - I notice you use total in two ways - that is
at best injudicious; change one of them, to be safe.

It seems illogical to use parseFloat on something just shown to be
integer; you could use unary + instead; you don't need that line, unless
you must allow trailing characters.

Get a proper newsreader, with spelling-checker; Google is a bad
interface; read newsgroup FAQ 2.3, 4.6, 4.7 before posting a reply.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
May 10 '06 #8
I wrote a basic code because the real code has so much other stuff
going on. My code allows the user to add as many lines of items to be
purchased...so I have no idea how many items to total up for line item
or main total, so this statement gets all the sets of values.
The problem is only seen when 3 or 6 items are purchased at a cost of
..70 cents...that's the only time it's wrong.
My code gives the following totals
3 * .70 = 2.09
6 * .70 = 4.19

btw, I'm not asking for anyone's thoughts using eval...I had no choice
but to use it, the information is coming from some visual basic
statements and would not work without the eval...I also had to use the
Visual Basic to create collapsible / expandable items to be purchased
area.

My code:
for(i=2;i<=nrow;i++) {
eval("quant" + i + "=document.RFO.quant_" + i + ".value");
eval("unit" + i + "=document.RFO.unit_" + i + ".value");
eval("tot" + i + "=0");

eval("tquant=quant" + i + "");
eval("tunit=unit" + i + "");
eval("ttot=tot" + i + "");

if(isPositiveInteger(tquant))
{
tquant=parseFloat(tquant)
{
ttot=tquant * tunit;
}
}
eval("document.RFO.tot_" + i + ".value=format(ttot)");
}
For testing, I have stripped to code down to nothing which only ran on
the first set of values...the code I listed before...and I get the same
results. I then changed it a bit after reading your statments
here...even removing the isPositiveInteger statment to make sure the
problem was not there. I still get the same result, every combination
of values work except 3 or 6 items at a price of ".70" or ".7"

function calculateCost()
{
nrow=document.RFO.nrow.value;
quant1=document.RFO.quant_1.value;
unit1=document.RFO.unit_1.value;
tot1=0;
quant1=parseInt(quant1)
unit1=parseFloat(unit1)
{
tot1=quant1 * unit1;
}
}
document.RFO.tot_1.value=format(tot1)

May 10 '06 #9
if(isPositiveInteger(tquant))
{
document.RFO.elements["tot_"+i].value=tquant*tunit;
}

You haven't shown us your format() function. As suggested
before, run without it to determine if it's the problem.


keep reading...I removed the function as well as other stuff to test
the code.

May 10 '06 #10
ey****@ncsa.uiuc.edu wrote:
I wrote a basic code because the real code has so much other stuff
going on. My code allows the user to add as many lines of items to be
purchased...so I have no idea how many items to total up for line item
or main total, so this statement gets all the sets of values.
The problem is only seen when 3 or 6 items are purchased at a cost of
.70 cents...that's the only time it's wrong.
My code gives the following totals
3 * .70 = 2.09
6 * .70 = 4.19 <snip> function calculateCost()
{
nrow=document.RFO.nrow.value;
quant1=document.RFO.quant_1.value;
unit1=document.RFO.unit_1.value;
tot1=0;
quant1=parseInt(quant1)
unit1=parseFloat(unit1)
{
tot1=quant1 * unit1;
}
}
document.RFO.tot_1.value=format(tot1)


Once again the output from this function should not be expected to
produce differing results for input of quantity '3' or '6' and unit
price '.7' and '.70', and it does not:-

function cCost() {
quant1= '3';
unit1= '.7';
tot1=0;
quant1=parseInt(quant1)
unit1=parseFloat(unit1)
{
tot1=quant1 * unit1;
}
return tot1;
}
function cCost2() {
quant1= '3';
unit1= '.70';
tot1=0;
quant1=parseInt(quant1)
unit1=parseFloat(unit1)
{
tot1=quant1 * unit1;
}
return tot1;
}

alert(cCost()+'\n'+cCost2());
/*
alerts:-
2.0999999999999996
2.0999999999999996
*/

With input values both '.7' and .07' the output is the same number.

You will not be able to attribute the problem unless you post some code
that demonstrates it.

Richard.

May 10 '06 #11
JRS: In article <e3*******************@news.demon.co.uk>, dated Tue, 9
May 2006 22:29:06 remote, seen in news:comp.lang.javascript, Richard
Cornford <Ri*****@litotes.demon.co.uk> posted :

(Incidentally, although the FAQ reference VK posted is relevant to the
issues of money calculations and number to formatted string
transformations, it cannot account for the symptoms you describe. VK
should generally be ignored, he does not know javascript at all and as a
result he cannot see what would be expected from executing javascript
code, and so is incapable of attributing effects to causes except by
(inevitably often wrong) guess-work.)


<FAQENTRY>

FAQ 4.6 should, to allow for the limitations of new arrivals, cite FAQ
4.7. 4.7 indicates why rounding (rather than truncation) is needed even
for calculations nominally exact in pennies.

Append ' <i>ff.</i>' to the line containing the first URL.

2.6 para 2 sentence 2 word 11 seems too short (in my WWW copy). The
error was introduced in version 8.0.

</FAQENTRY>
Anyone citing the FAQ to a Googler should generally cite also FAQ 2.3;
paragraph numbering within 2.3 would be helpful (just do it manually in
the source).

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
May 10 '06 #12
I used the same code you used above...and got the same conclusiong.
3 * .7 = 2.0999999999999996
6 * .7 = 4.199999999999999
WRONG ANSWERS

A correct response should be:
3 * .7 = 2.10
6 * .7 = 4.20

The above code gives the correct resonse to all other calculations that
I have tried.

May 10 '06 #13
ey****@ncsa.uiuc.edu writes:
btw, I'm not asking for anyone's thoughts using eval...
You don't have to ask :)
I had no choice but to use it,
"I have been driven many times upon my knees by the overwhelming
conviction that I had nowhere else to go." - Abraham Lincoln
eval("quant" + i + "=document.RFO.quant_" + i + ".value");


Try:
window["quant"+i] = document.RFO["quant_"+i].value;
or more standards compliant:
window["quant"+i] = document.forms['RFO'].elements['quant_'+i].value;

We don't want to give people the idea that they have to use eval
for property access.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
May 10 '06 #14
eval()'s removed...the problem is still there.

May 10 '06 #15
The Question again.....

function cCost() {
quant1= '3';
unit1= '.7';
tot1=0;
quant1=parseInt(quant1)
unit1=parseFloat(unit1)
{
tot1=quant1 * unit1;
}
return tot1;
}
function cCost2() {
quant1= '6';
unit1= '.70';
tot1=0;
quant1=parseInt(quant1)
unit1=parseFloat(unit1)
{
tot1=quant1 * unit1;
}
return tot1;
}
alert(cCost()+'\n'+cCost2());
/*
alerts:-
2.0999999999999996
4.199999999999999
*/
3 * .7 = 2.0999999999999996
6 * .7 = 4.199999999999999
WRONG ANSWERS

Use your calculators
A correct response should be:
3 * .7 = 2.10
6 * .7 = 4.20
The above code gives the correct resonse to all other calculations that

I have tried.

May 10 '06 #16
ey****@ncsa.uiuc.edu writes:
The Question again.....
What question? I see no question here.
function cCost() {
quant1= '3';
unit1= '.7';
tot1=0;
quant1=parseInt(quant1)
unit1=parseFloat(unit1)
It is sufficient, and equivalent, to write;
quant1 = 3;
unit1 = 0.7;
Parsing from a string gives the same value as parsing the
literal.

3 * .7 = 2.0999999999999996
6 * .7 = 4.199999999999999
WRONG ANSWERS
Wrong question.

You write ".7" and have it parsed to a double precission floating
point number (the only number type in Javascript).
Since 7/10 is not exactly representable as a double, the value of
the literal becomes the closest representable value, which is
sligtly less than 7/10. Let's call it 7/10-epsilon.

You then multiply this value by 3 (which can be represented exactly)
and the result is 21/10-3*epsilon.

Multipliciation increases the error. For laughs, try displaying;
2.1-3*0.7

You then try to convert this value back to a string displaying a
decimal representation of the number. That is the value you see.
it's far enough from 2.1 to not be show as that.
The above code gives the correct resonse to all other calculations that
I have tried.


Try some more. It's a general problem. Do not use fractional numbers
if you need exact results.

I believe using floating point numbers for monetary calculations is
even illegal in some cases (without knowing which :).

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
May 10 '06 #17
ey****@ncsa.uiuc.edu wrote:
I used the same code you used above...and got the same
conclusiong.
3 * .7 = 2.0999999999999996
6 * .7 = 4.199999999999999
WRONG ANSWERS
How can they be the wrong answers? They are the numbers generated by the
operations used in _your_ - calculateCost - function when given the
parameters you specified, and they are the numbers expected given that
the calculations are performed with IEEE double precision floating point
arithmetic and baring in mind that that number format is not capable of
representing all numeric values precisely (as no number format is).

I posted those functions to demonstrate that the issue you stated; that
you got differing results depending on whether the input was '.7' or
'.70', was not manifest in the code you posted. The training zero digit
on the input does not alter the numbers generated by the operations
used.
A correct response should be:
3 * .7 = 2.10
6 * .7 = 4.20
Neither of those numbers can be represented by an IEEE double precision
floating point number (in just the same way as a decimal format cannot
precisely represent 1/3).

If you mean that you want the formatted _string_ output to be '2.10' and
'4.20' from the numbers 2.0999999999999996 and 4.199999999999999
respectively then you need a (decent) number to string formatting
function. Or the one you have (the one you have been repeatedly asked to
post) is not suited to its task.
The above code gives the correct resonse to all other
calculations that I have tried.


There is no code in your post, 'above' or otherwise.

Richard.
May 10 '06 #18
ey****@ncsa.uiuc.edu wrote:
The Question again..... [...]
3 * .7 = 2.0999999999999996
6 * .7 = 4.199999999999999
WRONG ANSWERS

Use your calculators
A correct response should be:
3 * .7 = 2.10
6 * .7 = 4.20
The above code gives the correct resonse to all other calculations that

I have tried.


You were pointed to FAQ 4.6: How do I convert a Number into a String
*with exactly 2 decimal places*?

The explanation is there: "Rounding of x.xx5 is uncertain, as such
numbers are not represented exactly."

The very next FAQ 4.7: "Why does 5 * 1.015 != 5.075 or 0.05+0.01 !=
0.06?" also fits your question:

" Javascript numbers are represented in binary as IEEE-754 Doubles,
with a resolution of 53 bits, giving an accuracy of 15-16 decimal
digits; integers up to about 9e15 are precise, but few decimal
fractions are. Given this, arithmetic is as exact as possible,
but no more. Operations on integers are exact if the true result
and all intermediates are integers within that range.

"In particular, non-integer results should not normally be compared
for equality; and non-integer computed results generally need
rounding; see 4.6."
Search this news group for questions on rounding, you will find this
topic discussed at length and also that you are not alone in your
frustration and confusion. :-)
--
Rob
Group FAQ: <URL:http://www.jibbering.com/faq/>
May 10 '06 #19
JRS: In article <11**********************@v46g2000cwv.googlegroups .com>
, dated Wed, 10 May 2006 10:08:51 remote, seen in
news:comp.lang.javascript, Richard Cornford
<Ri*****@litotes.demon.co.uk> posted :
function calculateCost()
...
document.RFO.tot_1.value=format(tot1)


Once again the output from this function should not be expected to
produce differing results for input of quantity '3' or '6' and unit
price '.7' and '.70', and it does not:-


But you did not use format.

In code posted by an inexperienced or naive user, one should half-expect
that code formatting float dollars to dollars point integer cents will
be wrong.

The code earlier recommended in this group was wrong (I can't recall
whether it was in the FAQ; ISTR that it failed with 0.07).

Code posted here by newcomers since the present FAQ 4.6 was written has
been wrong.

The OP's job should evidently produce exact integer cents as a result of
the arithmetic, if implemented in decimal arithmetic. It may well be
that it actually produces, sometimes, an undersize Double, and that the
OP's format includes Math.floor().

If there is a difference in numerical value between input strings ".7"
and ".70". then the OP has a problem outside format.
To get anywhere, the OP should either learn javascript including the
implications of using IEEE Doubles, or he should post a cut-down version
of his code, complete and ready to run, with an exact statement of
sample data that it uses and what good and bad results that data gives.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
May 10 '06 #20
JRS: In article <11**********************@y43g2000cwc.googlegroups .com>
, dated Wed, 10 May 2006 07:59:33 remote, seen in
news:comp.lang.javascript, ey****@ncsa.uiuc.edu posted :

You were asked to read the FAQ before posting a reply. If you had done
so, you should have learned how to format newsgroup replies. Read
section 2.3 now.

I wrote a basic code because the real code has so much other stuff
going on. My code allows the user to add as many lines of items to be
purchased...so I have no idea how many items to total up for line item
or main total, so this statement gets all the sets of values.
The problem is only seen when 3 or 6 items are purchased at a cost of
.70 cents...that's the only time it's wrong.
My code gives the following totals
3 * .70 = 2.09
6 * .70 = 4.19
This document.writeln(3*.70, ", ", 6*.70)
gives 2.0999999999999996, 4.199999999999999
Read FAQ 4.7, and my site, to see why.

Evidently, your format function truncates. You should have posted
it or replaced it with a known-good, tested one.

Read FAQ 4.6, and my site, on rounding from Number to String.

btw, I'm not asking for anyone's thoughts using eval...
You get what you need, which is not necessarily what you want.
I had no choice
but to use it, the information is coming from some visual basic
statements and would not work without the eval...
It's rarely necessary to use eval; it appears to be so to you because
you are inadequately informed. Read FAQ 4.40, 4.39, and cited notes.
I also had to use the
Visual Basic to create collapsible / expandable items to be purchased
area.


That you used it is credible, but that you needed to is not.

But thank you for so amply illustrating a point that I made recently.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
May 10 '06 #21
JRS: In article <ej**********@hotpop.com>, dated Wed, 10 May 2006
22:44:16 remote, seen in news:comp.lang.javascript, Lasse Reichstein
Nielsen <lr*@hotpop.com> posted :

I believe using floating point numbers for monetary calculations is
even illegal in some cases (without knowing which :).


That should not be possible[*].

Decimal floating point does not show the problem in the same manner
(unless I/O uses some other base); and IEEE Doubles are perfectly
adequate for monetary calculations if used intelligently (i.e. for
integers in the range within +-2^53, which is I think enough to
represent the world "GNP" in eurocents).

There was a strict legal requirement on conversions among fixed-parity
euroland currencies and between them and the euro, mostly relevant
around 1999-2002 IIRC; and it would be difficult for the average
programmer to be certain of absolute compliance if working in non-
decimal arithmetic.

But doing accountancy arithmetic in binary using internal units greater
than the required resolution is undoubtedly unwise.

Budgetary arithmetic is another matter, of course : "a billion here, a
billion there; it soon adds up to real money" <paraquote>.
[*] And Pi != 3.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.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)
May 11 '06 #22
JRS: In article <11*********************@i40g2000cwc.googlegroups. com>,
dated Wed, 10 May 2006 12:55:07 remote, seen in
news:comp.lang.javascript, ey****@ncsa.uiuc.edu posted :
eval()'s removed...the problem is still there.


Of course. Your real problem has been personal ignorance combined with
an unwillingless to accept the advice which you have been given. It may
be combined with an inability to learn; but it's hard to distinguish
that from mere obstinacy.

The results of your arithmetic manipulations, before format, are
necessarily inexact; you have chosen to work in a unit that you need to
represent hundredths of, and you are using a binary number
representation in which 96% of hundredths cannot be represented exactly.

You have chosen to display those results, which are close approximations
to the ideal, by a method which, at least sometimes, truncates removing
0.999... pennies. You see the consequences.

Post your format function.

Moreover, you're still not complying with FAQ 2.3.

One can only hope that you are a sophomore or janitor, and not a member
of the teaching staff or an employee of a computer service.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
May 11 '06 #23
Lasse Reichstein Nielsen wrote:
ey****@ncsa.uiuc.edu writes:
eval("quant" + i + "=document.RFO.quant_" + i + ".value");


Try:
window["quant"+i] = document.RFO["quant_"+i].value;
or more standards compliant:
window["quant"+i] = document.forms['RFO'].elements['quant_'+i].value;

We don't want to give people the idea that they have to use eval
for property access.


And we don't want to give them the idea that `window' is
a generally available reference for that purpose either:

var _global = this;

function ...(...)
{
// ...
_global["quant" + i] =
document.forms['RFO'].elements['quant_' + i].value;
// ...
}
PointedEars
May 18 '06 #24
Thomas 'PointedEars' Lahn said the following on 5/18/2006 11:50 AM:
Lasse Reichstein Nielsen wrote:
ey****@ncsa.uiuc.edu writes:
eval("quant" + i + "=document.RFO.quant_" + i + ".value");

Try:
window["quant"+i] = document.RFO["quant_"+i].value;
or more standards compliant:
window["quant"+i] = document.forms['RFO'].elements['quant_'+i].value;

We don't want to give people the idea that they have to use eval
for property access.


And we don't want to give them the idea that `window' is
a generally available reference for that purpose either:


And once again, name a *BROWSER* that doesn't use window as the global
object. After all, this group is mainly geared towards browsers and
Internet web sites.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
May 18 '06 #25
VK

Randy Webb wrote:
And once again, name a *BROWSER* that doesn't use window as the global
object.


That was easy: Internet Explorer 4.0 or higher. You meant to say "a
browser not having window object among host objects". That's indeed
/very/ challenging. Yet Mr. Lahn's beloved spooky-booh is "there is
Global object but there is not window object".

May 18 '06 #26
VK said the following on 5/18/2006 3:06 PM:
Randy Webb wrote:
And once again, name a *BROWSER* that doesn't use window as the global
object.
That was easy: Internet Explorer 4.0 or higher.


Really? So in IE4 or higher, this will produce different results:

var myVar = 'something';
var _global = this;
alert(window[myVar]);
alert(_global[myVar]);

Different results eh?
You meant to say "a browser not having window object among host objects".
No, I meant "a browser where window does not refer to the global object".
That's indeed /very/ challenging.
No more challenging than what I asked.
Yet Mr. Lahn's beloved spooky-booh is "there is Global object but there
is not window object".


The same spooky-booh can be said about a Global object as well.

Prove that every UA in existence has a Global object.

Now there is a challenge. It can no more be proven than the opposite can
be proven with access to every UA available.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
May 18 '06 #27
VK

Randy Webb wrote:
VK said the following on 5/18/2006 3:06 PM:
Randy Webb wrote:
And once again, name a *BROWSER* that doesn't use window as the global
object.


That was easy: Internet Explorer 4.0 or higher.


Really? So in IE4 or higher, this will produce different results:

var myVar = 'something';
var _global = this;
alert(window[myVar]);
alert(_global[myVar]);

Different results eh?


Oh com'on... There was a discussion already with the participation of
Mr. Cornford and all MSDN links. If Microsoft itself says that Global
object and window object are not the same, Mr. Webb's opinion will not
change the picture.

Actually Global === window is a bogus in Gecko either, a nice imitation
atop of the reality to "visually" conform with ECMA specs.

I promised to show how to use parallel Global spaces to implement
private/protected members a while ago. It just happens that your own
things may get not really your own if you are not careful enough :-(
Now the problem is solved. Here is "Ajax" behavior you are free to
attach to any amount of block elements on the page like say DIV. Of
course you should set URI attribute for each element to some existing
file/url. You also can set optional RATE attribute to define refresh
rate (3sec default).

Please note that within the binding there is Global space. For each
bound element there is its own Global space from where you still can
address window host object. At the same time these Global spaces are
not visible to /that/ Global space which is "the same as window
object". It doesn't see any of global variables in these parallel
spaces and it can communicate with them only over pre-defined public
methods. The same story with the binding part for Gecko (coming soon if
one wants).

"Welcome to the real world, Neo"
("Matrix" movie)
;-)

// sample HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Bx2</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<style type="text/css">
body {
font: 1em Verdana, Geneva, sans-serif;
color: #000000;
background-color: #FFFFFF;
}

p {
width: 50%;
height: 10em;
overflow: auto;
margin: 0.5em 0.5em;
border: thin inset;
padding: 0.5em 0.5em;
}

#test {
behavior: url(ajax.htc);
}
</style>
</head>

<body>

<p id="test" uri="test.txt">No content</p>

</body>
</html>

// ajax.htc

<?xml version="1.0"?>
<!--
**
* Bx2 Twinpair::HTC
* IXMLHTTPRequest
*
* VK [sc**********@yahoo.com]
-->

<public>
<component>
<method name="setRequest" />
<method name="start" />
<method name="stop" />

<property name="randomizeURI"
value="yes" />
<property name="lastError"
value=""
get="getError"
put="readOnly" />

<attach
event="oncontentready"
onevent="constructor()" />
<attach
event="ondetach"
onevent="destructor()" />
</component>
<script type="text/Jscript"><!--

var $errors = [
"",
"Couldn't instantiate IXMLHTTPRequest object",
"Connection error"
];

var $err = $errors[0];

var $URI = '';

var $req = null;

var $callback = null;

var $rate = 3;

var $timer = null;
try {
$req = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e) {
$err = $errors[1] + ': ' + e.message;
}

if (($req == null)&&('undefined' != typeof XMLHttpRequest)) {
/* in hope of IE7 or higher */
try {
$req = new XMLHttpRequest();
}
catch(e) {
$err = $errors[1] + ': ' + e.message;
}
}

$callback = function() {
if ($req.readyState == 4) {
if (($req.status == 200)||($req.status == 0)) {
$err = $errors[0];
element.innerHTML = $req.responseText;
}
else if (($req.status == 204)||($req.status == 304)) {
$err = $errors[0];
}
else {
$err = $errors[2] + ': ' + $req.statusText;
}
if ($rate) {
$timer = window.setTimeout(this.makeRequest,$rate*1000);
}
}
}
function constructor() {
$URI = element.getAttribute('URI',2) || '';
$rate = parseInt(element.getAttribute('RATE'),10) || 3;
if ($URI != '') {
makeRequest();
}
}
function destructor() {
if ($timer != null) {
window.clearTimeout($timer);
}
if ($req.readyState != 4) {
$req.abort();
}
}
function setRequest(URI, RATE) {
$URI = URI || '';
$rate = isNaN(parseInt(RATE,10)) ? 3 : RATE;
}
function makeRequest() {
if ('yes' == element.randomizeURI) {
var rnd = ($URI.lastIndexOf('?') != -1)
? ('&rnd='+(new Date()).getTime())
: ('?rnd='+(new Date()).getTime());
var URI = $URI + rnd;
}
else {
var URI = $URI;
}
$req.open('GET', URI, true);
$req.onreadystatechange = $callback;
$req.send('');
}
function start() {
makeRequest();
}
function stop() {
if ($timer != null) {
window.clearTimeout($timer);
}
}
function getError() {
return $err;
}
function readOnly(val) {
return val;
}

//--></script>
</public>

May 18 '06 #28
VK wrote on 18 mei 2006 in comp.lang.javascript:
If Microsoft itself says that Global
object and window object are not the same, Mr. Webb's opinion will not
change the picture.


Microsoft != God

Picture that!

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
May 18 '06 #29
VK
A long code can be easily mangled on copy'n'paste over Usenet. So here
the whole relevant working demo:

<http://www.geocities.com/schools_ring/bx2/ajax_ie.zip>

P.S. Please trust me that I will not use this opportunity to show you
how vulnerable IE is :-)

May 18 '06 #30
VK wrote:
Randy Webb wrote:
And once again, name a *BROWSER* that doesn't use window as the
global object.
That was easy: Internet Explorer 4.0 or higher.


Nonsense.
You meant to say "a browser not having window object among host objects".
That's indeed /very/ challenging. Yet Mr. Lahn's beloved spooky-booh
is "there is Global object but there is not window object".


You got my point -- almost. `window' is a host-defined property of the
Global Object, a reference to a host object; not a built-in reference to a
native object. However, one can /not/ expect a host object to work like a
native object, including augmentation with new properties. See the
ECMAScript Language Specification, Edition 3 Final, 4.3.8 (Definitions:
Host Object) and 8.6.2 (Internal Properties and Methods).
PointedEars
May 18 '06 #31
VK
VK wrote on 18 mei 2006 in comp.lang.javascript:
If Microsoft itself says that Global
object and window object are not the same, Mr. Webb's opinion will not
change the picture.


Microsoft != God


I /never/ stated the opposite. Mozilla is not God neither (equivalent
binding for Gecko browsers will follow).

"God is dead"
Nietzsche

"What we call matter is a certain systematic combination of the
elements (sensations)"
Mach

:-)

May 18 '06 #32
VK wrote on 18 mei 2006 in comp.lang.javascript:
VK wrote on 18 mei 2006 in comp.lang.javascript:
> If Microsoft itself says that Global
> object and window object are not the same, Mr. Webb's opinion will not
> change the picture.
Microsoft != God


I /never/ stated the opposite.


You used MSes word for infallible final argument.
I objected to MS being the global object.
Mozilla is not God neither (equivalent
binding for Gecko browsers will follow).
Mozilla is dead, Firefox is it's phoenix.
"God is dead", Nietzsche
And God said: "Nietzsche is dead". And it was likewize.

"What we call matter is a certain systematic combination of the
elements (sensations)"
Mach


What we call Micosoft is neiter the measure of things nor always wrong.

However this matter doesn't matter in practice.

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
May 18 '06 #33
VK wrote:
Randy Webb wrote:
VK said the following on 5/18/2006 3:06 PM:
Randy Webb wrote:
And once again, name a *BROWSER* that doesn't use
window as the global object.
>
> That was easy: Internet Explorer 4.0 or higher.
Really? So in IE4 or higher, this will produce different
results:

var myVar = 'something';
var _global = this;
alert(window[myVar]);
alert(_global[myVar]);

Different results eh?


Oh com'on... There was a discussion already with the
participation of Mr. Cornford


You mean the thread where you made some claims about IE and failed to
demonstrate an concrete reality in those claims and I posted a
demonstration that the object referred to by the global window property
and the ECMAScript global object in IE were indistinguishable?

< news:du*******************@news.demon.co.uk >
and all MSDN links.
One reference to an MSDN article that stated the consequences of some
internal implementation details in IE, and I then posted code that
demonstrated that those consequences were false in IE.

< news:du*******************@news.demon.co.uk >

I realise that your grasp of logic is defective but if you cannot
produce _anything_ to demonstrate your claims you should stop making
them.
If Microsoft itself says that Global object and window
object are not the same, Mr. Webb's opinion will not
change the picture.
Microsoft did not make that claim. It is your interpretation of what
they wrote in a page that has been demonstrated to be, at minimum,
incorrect in its conclusions. You have repeatedly demonstrated that your
interpretation of written English is so poor that you cannot understand
what others write so there is little point in your posting conclusions
based upon your faulty interpretations of documents unless you can back
them up with concrete demonstrations of your reality.
Actually Global === window is a bogus in Gecko either, a nice
imitation atop of the reality to "visually" conform with ECMA
specs.
And that claim also evaporated when you made it in the previous thread.
I promised to show how to use parallel Global spaces to
implement private/protected members a while ago.

<snip>

Nobody else cares. You are the only person perverse enough to attempt to
reproduce a capability that is inherit in the language by specification,
and do so in a way that is dependent upon the host environment,
differently dependent in different host environments (requiring separate
implementations for each environment), smeared in little chunks
throughout the document and several subsidiary files, and only possible
in precisely two host environments. Another example of your preferring
to things in the worst possible way available.

Richard.
May 18 '06 #34
VK

Richard Cornford wrote:
You mean the thread where you made some claims about IE and failed to
demonstrate an concrete reality in those claims


I explained the reason of the delay, but you are free to not believe
me. Now take the sample I linked and try it.

And there is a code with equal behavior for Gecko browsers (Firefox,
Mozilla Suite, Camino, Netscape 8 in Gecko mode). I would never post an
IE-only solution or proof of anything in c.l.j.

May 18 '06 #35
VK wrote:
Richard Cornford wrote:
VK wrote:
Randy Webb wrote:
VK said the following on 5/18/2006 3:06 PM:
> Randy Webb wrote:
>> And once again, name a *BROWSER* that doesn't use ^^^^^^^^^^^>> window as the global object. ^^^^^^^^^^^^^^^^^^^^^^^^^^^>
> That was easy: Internet Explorer 4.0 or higher. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Really? So in IE4 or higher, this will produce different
results:

var myVar = 'something';
var _global = this;
alert(window[myVar]);
alert(_global[myVar]);

Different results eh? ^^^^^^^^^^^^^^^^^^^^
Oh com'on... There was a discussion already with the ^^^^^^^^^^^^^^^^^^^^^^^^ participation of Mr. Cornford
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
You mean the thread where you made some claims about IE ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ and failed to demonstrate an concrete reality in those claims ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^
<snip> < news:du*******************@news.demon.co.uk >
I explained the reason of the delay, but you are free to not
believe me.
What delay, and in what? You have never demonstrated any difference
between the object referred to by the global window property and the
ECMAScript global object in IE, and you have never proposed that you
will do so, and if you had we would still be waiting.
Now take the sample I linked and try it.

<snip>

That script has no relevance to the issue. (Or anything else for that
matter).

Richard.
May 18 '06 #36

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

15 posts views Thread by Sven Templin | last post: by
65 posts views Thread by Pmb | last post: by
7 posts views Thread by aagarcia | last post: by
4 posts views Thread by Matt Billock | last post: by
4 posts views Thread by Joe-Paul | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.