How do I add a photo to my comment or blog entry?
problem with javascript in asp not rounding up..
Hello Guest
  
  • Login
• Register…
• Start blog
  • Who, Where, When
• What can I do?
• What to Read?
  • Polls
• Avatars
• Interests
  • Cities and Countries
• Random blog
• Users search
  • Search
• Games
• Tests
• QAIX
  • Сообщества
• Talxy Chat
• Horoscope
• Online
 
Зарегистрируйся!

QAIX > ASP web-programming > problem with javascript in asp not rounding up.. 23 August 2008 16:58:50

  Recent blog posts: 
  Forums:   
  Discuss: 
  Recent forum topics: 
  Recent forum comments:
  Moderators:

problem with javascript in asp not rounding up..

Gtn170777 23 August 2008 16:58:50
 Hi All,

I have a neat little script that calculates price based on quantity without
refreshing the page.. the script is -

<script type="text/javascri­pt">
function OpenWin(url)
{
window.open(url,'wi­n','scrollbars=1,sta­tus=0,resizable=0,wi­dth=200,height=265')­;
}


function btnCalculate_onclic­k()
{
var numQty;
var adprice;

if (isNaN(document.frm­Client.txtQty.value)­)
{
alert('Please enter a number for advert quantity.');
}
else
{
numQty = parseInt(document.f­rmClient.txtQty.valu­e);
adprice = parseInt(document.f­rmClient.adprice.val­ue);

if((numQty >= 1) && (numQty <= 1)){
document.getElement­ById('divPrice').inn­erHTML = ' ' + adprice + ' + VAT';
document.getElement­ById('maindivPrice')­.innerHTML = ' ' +
Math.round(100*(adp­rice * numQty))/100 + ' + VAT';
} else if((numQty >= 2) && (numQty <= 10)){
document.getElement­ById('divPrice').inn­erHTML = ' ' +
(Math.round(adprice­ * numQty)*.95)/numQty­ + ' + VAT';
document.getElement­ById('maindivPrice')­.innerHTML = ' ' +
Math.round(adprice * numQty)*.95 + ' + VAT';
} else if((numQty >= 11) && (numQty <= 20)){
document.getElement­ById('divPrice').inn­erHTML = ' ' +
(Math.round(adprice­ * numQty)*.85)/numQty­ + ' + VAT';
document.getElement­ById('maindivPrice')­.innerHTML = ' ' +
Math.round(adprice * numQty)*.85 + ' + VAT';
} else if((numQty >= 21) && (numQty <= 30)){
document.getElement­ById('divPrice').inn­erHTML = ' ' +
(Math.round(adprice­ * numQty)*.75)/numQty­ + ' + VAT';
document.getElement­ById('maindivPrice')­.innerHTML = ' ' +
Math.round(adprice * numQty)*.75 + ' + VAT';
} else if((numQty >= 31) && (numQty <= 50)){
document.getElement­ById('divPrice').inn­erHTML = ' ' +
(Math.round(adprice­ * numQty)*.5)/numQty + ' + VAT';
document.getElement­ById('maindivPrice')­.innerHTML = ' ' +
Math.round(adprice * numQty)*.5 + ' + VAT';
} else {
alert("Please contact us for more information about the benefits of our
monthly account packages.");
}
}
}</script>

The problem I have is that it doesn't round up, for instance in stead of
0.95 i get 0.9499999999998.

Does anyone have any ideas how to fix this?

Many thanks
Add comment
Adrienne Boswell 22 August 2008 16:01:23 permanent link ]
 Gazing into my crystal ball I observed =?Utf-8?B?R1ROMTcwN­zc3?=
<GTN170777@discussi­ons.microsoft.com> writing in
news:443E2509-7F0E-­4CEC-B243-D6EDC931DB­7F@microsoft.com:

ASP has no knowledge of the client, this is a client side issue.
Followups set to comp.lang.javascrip­t.

Hi All,
I have a neat little script that calculates price based on quantity
without refreshing the page.. the script is -
<script type="text/javascri­pt">
function OpenWin(url)
{
window.open(url,'wi­n','scrollbars=1,sta­tus=0,resizable=
0,widt
h=200,height=265');­
}
function btnCalculate_onclic­k()
{
var numQty;
var adprice;
if (isNaN(document.frm­Client.txtQty.value)­)
{
alert('Please enter a number for advert quantity.');
}
else
{
numQty = parseInt(document.f­rmClient.txtQty.valu­e);
adprice = parseInt(document.f­rmClient.adprice.val­ue);
if((numQty >= 1) && (numQty <= 1)){
document.getElement­ById('divPrice').inn­erHTML = 'бё' + adprice + '
+ VAT'; document.getElement­ById('maindivPrice')­.innerHTML = 'бё' +
Math.round(100*(adp­rice * numQty))/100 + ' + VAT';
} else if((numQty >= 2) && (numQty <= 10)){
document.getElement­ById('divPrice').inn­erHTML = 'бё' +
(Math.round(adprice­ * numQty)*.95)/numQty­ + ' + VAT';
document.getElement­ById('maindivPrice')­.innerHTML = 'бё' +
Math.round(adprice * numQty)*.95 + ' + VAT';
} else if((numQty >= 11) && (numQty <= 20)){
document.getElement­ById('divPrice').inn­erHTML = 'бё' +
(Math.round(adprice­ * numQty)*.85)/numQty­ + ' + VAT';
document.getElement­ById('maindivPrice')­.innerHTML = 'бё' +
Math.round(adprice * numQty)*.85 + ' + VAT';
} else if((numQty >= 21) && (numQty <= 30)){
document.getElement­ById('divPrice').inn­erHTML = 'бё' +
(Math.round(adprice­ * numQty)*.75)/numQty­ + ' + VAT';
document.getElement­ById('maindivPrice')­.innerHTML = 'бё' +
Math.round(adprice * numQty)*.75 + ' + VAT';
} else if((numQty >= 31) && (numQty <= 50)){
document.getElement­ById('divPrice').inn­erHTML = 'бё' +
(Math.round(adprice­ * numQty)*.5)/numQty + ' + VAT';
document.getElement­ById('maindivPrice')­.innerHTML = 'бё' +
Math.round(adprice * numQty)*.5 + ' + VAT';
} else {
alert("Please contact us for more information about the benefits
of our
monthly account packages.");
}
}
}</script>
The problem I have is that it doesn't round up, for instance in stead
of бё0.95 i get бё0.9499999999998.
Does anyone have any ideas how to fix this?
Many thanks



--
Adrienne Boswell at Home
Arbpen Web Site Design Services
http://www.cavalcad­e-of-coding.info
Please respond to the group so others can share

Add comment
Dave Anderson 22 August 2008 16:44:16 permanent link ]
 "GTN170777" wrote:
The problem I have is that it doesn't round up, for instance
in stead of 0.95 i get 0.9499999999998.
Does anyone have any ideas how to fix this?

Yes. Avoid using binary digits to represent non-integer rational numbers.

But if you want to use IEEE 754 floating point numbers (as ECMA-262v3
conforming languages do), then you will have to accept that arithmetic
operators introduce computational rounding error.

On the bright side, that error is so small that you can get a string
representation of the value you desire by using Number.ToFixed():

http://msdn.microso­ft.com/en-us/library­/sstyff0z(VS.85).asp­x



--
Dave Anderson

Unsolicited commercial email will be read at a cost of $500 per message. Use
of this email address implies consent to these terms.

Add comment
Anthony Jones 22 August 2008 17:12:20 permanent link ]
 "GTN170777" <GTN170777@discussi­ons.microsoft.com> wrote in message
news:443E2509-7F0E-­4CEC-B243-D6EDC931DB­7F@microsoft.com...
Hi All,
I have a neat little script that calculates price based on quantity
without
refreshing the page.. the script is -
<script type="text/javascri­pt">
function OpenWin(url)
{
window.open(url,'wi­n','scrollbars=1,sta­tus=0,resizable=0,wi­dth=200,height=26
5');
}
function btnCalculate_onclic­k()
{
var numQty;
var adprice;
if (isNaN(document.frm­Client.txtQty.value)­)
{
alert('Please enter a number for advert quantity.');
}
else
{
numQty = parseInt(document.f­rmClient.txtQty.valu­e);
adprice = parseInt(document.f­rmClient.adprice.val­ue);
if((numQty >= 1) && (numQty <= 1)){
document.getElement­ById('divPrice').inn­erHTML = 'ё' + adprice + ' +
VAT';
document.getElement­ById('maindivPrice')­.innerHTML = 'ё' +
Math.round(100*(adp­rice * numQty))/100 + ' + VAT';
} else if((numQty >= 2) && (numQty <= 10)){
document.getElement­ById('divPrice').inn­erHTML = 'ё' +
(Math.round(adprice­ * numQty)*.95)/numQty­ + ' + VAT';
document.getElement­ById('maindivPrice')­.innerHTML = 'ё' +
Math.round(adprice * numQty)*.95 + ' + VAT';
} else if((numQty >= 11) && (numQty <= 20)){
document.getElement­ById('divPrice').inn­erHTML = 'ё' +
(Math.round(adprice­ * numQty)*.85)/numQty­ + ' + VAT';
document.getElement­ById('maindivPrice')­.innerHTML = 'ё' +
Math.round(adprice * numQty)*.85 + ' + VAT';
} else if((numQty >= 21) && (numQty <= 30)){
document.getElement­ById('divPrice').inn­erHTML = 'ё' +
(Math.round(adprice­ * numQty)*.75)/numQty­ + ' + VAT';
document.getElement­ById('maindivPrice')­.innerHTML = 'ё' +
Math.round(adprice * numQty)*.75 + ' + VAT';
} else if((numQty >= 31) && (numQty <= 50)){
document.getElement­ById('divPrice').inn­erHTML = 'ё' +
(Math.round(adprice­ * numQty)*.5)/numQty + ' + VAT';
document.getElement­ById('maindivPrice')­.innerHTML = 'ё' +
Math.round(adprice * numQty)*.5 + ' + VAT';
} else {
alert("Please contact us for more information about the benefits of
our
monthly account packages.");
}
}
}</script>
The problem I have is that it doesn't round up, for instance in stead of
ё0.95 i get ё0.9499999999998.
Does anyone have any ideas how to fix this?

The short answer is do not concatenate a number directly in to a string use
the Number object's .toFixed method.

var n = 250 * 0.83
var s = n.toFixed(2)

However while I'm here have you noticed that the code in each of your Ifs
are identical except for that multiplier value changes? This pattern should
cause you to see a need for a function the can get the multiplier value. In
the code below I've refactored out a function which returns the discount for
a specified quantity. Note that by returning the actual discount in this
function it makes the relationship between the quantity and the discount
given much clearer.


I've made a business decision (which clearly you may disagree with) to
discount the unit price then multiply the quantity by the discounted price.
This is less likely to be disputed by a user IMO.

I use Math.round to ensure the discounted price is to the nearest penny.
That still doesn't eliminate the need to use .toFixed since Numbers are
stored as floating point values which cannot exactly represent numbers
exactly only to a reasonable degree of precision.


function btnCalculate_onclic­k()
{

var numQty = parseInt(document.f­rmClient.txtQty.valu­e);
var adprice = parseInt(document.f­rmClient.adprice.val­ue);

if (isNaN(numQty))
{
alert('Please enter a number for advert quantity.');
}
else
{
var multiplier = null;

try { multiplier = 1 - getDiscount(numQty)­ }
catch(e) { alert(e); }

if (multiplier)
{
var discountedUnitPrice­ = Math.round(adprice * multiplier * 100) / 100
document.getElement­ById('divPrice').inn­erHTML = 'ё' +
discountedUnitPrice­.toFixed(2) + '+ VAT';
document.getElement­ById('maindivPrice')­.innerHTML = 'ё' +
(discountedUnitPric­e * numQty).toFixed(2) + ' + VAT';
}
}
}

function getDiscount(numQty)­
{
if (numQty <= 1) return 0
if (numQty <= 10) return 0.05
if (numQty <= 20) return 0.15
if (numQty <= 30) return 0.25
if (numQty <= 50) return 0.5
throw "Please contact us for more information about the benefits of our
monthly account packages."
}



--
Anthony Jones - MVP ASP/ASP.NET


Add comment
Anthony Jones 22 August 2008 17:21:42 permanent link ]
 "Dave Anderson" <NPQRWPDWZGSP@spamm­otel.com> wrote in message
news:45GdnRjHjqH8Xz­PVnZ2dnUVZ_v3inZ2d@p­osted.visi...
"GTN170777" wrote:
The problem I have is that it doesn't round up, for instance
in stead of ё0.95 i get ё0.9499999999998.
Does anyone have any ideas how to fix this?
Yes. Avoid using binary digits to represent non-integer rational numbers.


How would one go about such an avoidance?

--
Anthony Jones - MVP ASP/ASP.NET


Add comment
Dave Anderson 22 August 2008 17:53:35 permanent link ]
 Anthony Jones wrote:
Yes. Avoid using binary digits to represent non-integer rational
numbers.
How would one go about such an avoidance?

There are boundless examples. My grandparents managed to avoid it their
entire lives.



--
Dave Anderson

Unsolicited commercial email will be read at a cost of $500 per message. Use
of this email address implies consent to these terms.


Add comment
Anthony Jones 22 August 2008 18:10:01 permanent link ]
 "Dave Anderson" <NPQRWPDWZGSP@spamm­otel.com> wrote in message
news:O2ngbbGBJHA.12­24@TK2MSFTNGP02.phx.­gbl...
Anthony Jones wrote:
Yes. Avoid using binary digits to represent non-integer rational
numbers.
How would one go about such an avoidance?
There are boundless examples. My grandparents managed to avoid it their
entire lives.


Great you've got plenty to choose from then, perhaps you could just present
just one?


--
Anthony Jones - MVP ASP/ASP.NET


Add comment
Dave Anderson 22 August 2008 18:59:22 permanent link ]
 Anthony Jones wrote:
Yes. Avoid using binary digits to represent non-integer rational
numbers.
How would one go about such an avoidance?
There are boundless examples. My grandparents managed to avoid it
their entire lives.
Great you've got plenty to choose from then, perhaps you could just
present just one?

MAN1: It hurts when I hit my fingers with a hammer.
MAN2: Try to avoid hitting your fingers.
MAN3: How could MAN1 do that?
MAN2: By not hitting them with a hammer.
MAN3: Can you give me examples? Just one?

Do you really want to go down this path, Anthony?



--
Dave Anderson

Unsolicited commercial email will be read at a cost of $500 per message. Use
of this email address implies consent to these terms.


Add comment
Dave Anderson 22 August 2008 19:16:18 permanent link ]
 Anthony Jones wrote:
...Numbers are stored as floating point values which cannot
exactly represent numbers exactly only to a reasonable degree
of precision...

This is not completely true. IEEE 754 double-precision floating point
numbers CAN and DO represent integers between -9007199254740992 and
9007199254740992 exactly. In addition, there are a whole bunch of
non-integer rational numbers that can be precisely represented.

Since you like examples, here's one:

EXAMPLE: 0.5



--
Dave Anderson

Unsolicited commercial email will be read at a cost of $500 per message. Use
of this email address implies consent to these terms.


Add comment
Anthony Jones 22 August 2008 21:54:22 permanent link ]
 "Dave Anderson" <NPQRWPDWZGSP@spamm­otel.com> wrote in message
news:uff9LAHBJHA.12­28@TK2MSFTNGP02.phx.­gbl...
Anthony Jones wrote:
Yes. Avoid using binary digits to represent non-integer rational
numbers.
How would one go about such an avoidance?
There are boundless examples. My grandparents managed to avoid it
their entire lives.
Great you've got plenty to choose from then, perhaps you could just
present just one?
MAN1: It hurts when I hit my fingers with a hammer.
MAN2: Try to avoid hitting your fingers.
MAN3: How could MAN1 do that?
MAN2: By not hitting them with a hammer.
MAN3: Can you give me examples? Just one?
Do you really want to go down this path, Anthony?


Yes, yes! Show me please a simple example of avoiding using binary digits
to represent a non-integer rational number?

--
Anthony Jones - MVP ASP/ASP.NET


Add comment
Anthony Jones 22 August 2008 22:01:47 permanent link ]
 "Dave Anderson" <NPQRWPDWZGSP@spamm­otel.com> wrote in message
news:eBkzpJHBJHA.33­48@TK2MSFTNGP04.phx.­gbl...
Anthony Jones wrote:
...Numbers are stored as floating point values which cannot
exactly represent numbers exactly only to a reasonable degree
of precision...
This is not completely true. IEEE 754 double-precision floating point
numbers CAN and DO represent integers between -9007199254740992 and
9007199254740992 exactly. In addition, there are a whole bunch of
non-integer rational numbers that can be precisely represented.

By 'numbers' I meant the whole set of numbers. Not just a finite few.


Since you like examples, here's one:
EXAMPLE: 0.5

I get the idea poor, choice of example though. 0.5 is a power of 2
therefore a mantissa with the value of 2 and an exponent of -1 exactly
represents 0.5. Mind you it was 20 years ago that I read the 754 spec I
could be wrong ;)


--
Anthony Jones - MVP ASP/ASP.NET


Add comment
Dave Anderson 22 August 2008 22:41:05 permanent link ]
 Anthony Jones wrote:
Do you really want to go down this path, Anthony?
Yes, yes! Show me please a simple example of avoiding using
binary digits to represent a non-integer rational number?

Since I cannot easily avoid representing text while posting to USENET, I
will not try. But I will offer a description of a real-world example:

<written on chalkboard> 7/3 </written on chalkboard>

You forgot to ask for EXACT representation, BTW.


--
Dave Anderson

Unsolicited commercial email will be read at a cost of $500 per message. Use
of this email address implies consent to these terms.


Add comment
Dave Anderson 22 August 2008 22:51:47 permanent link ]
 Anthony Jones wrote:
...Numbers are stored as floating point values which cannot
exactly represent numbers exactly only to a reasonable degree
of precision...
This is not completely true. IEEE 754 double-precision floating point
numbers CAN and DO represent integers between -9007199254740992 and
9007199254740992 exactly. In addition, there are a whole bunch of
non-integer rational numbers that can be precisely represented.
By 'numbers' I meant the whole set of numbers. Not just a finite few.

There is no way to represent every member of ANY infinite set with a finite
set of bits, so what else could you mean? Let's at least agree on this --
ECMA/J/JavaScript Number Objects can not represent more than 2^64 unique
values.


Since you like examples, here's one:
EXAMPLE: 0.5
I get the idea poor, choice of example though. 0.5 is a power of 2
therefore a mantissa with the value of 2 and an exponent of -1 exactly
represents 0.5.

Doesn't that actually make it an *illustrative* choice of example, since the
only non-integer rationals that can be precisely represented with IEEE 754
floats MUST have only powers of two in the denominator?



--
Dave Anderson

Unsolicited commercial email will be read at a cost of $500 per message. Use
of this email address implies consent to these terms.


Add comment
Anthony Jones 22 August 2008 23:28:03 permanent link ]
 "Dave Anderson" <NPQRWPDWZGSP@spamm­otel.com> wrote in message
news:OrBqF8IBJHA.34­00@TK2MSFTNGP05.phx.­gbl...
Anthony Jones wrote:
Do you really want to go down this path, Anthony?
Yes, yes! Show me please a simple example of avoiding using
binary digits to represent a non-integer rational number?
Since I cannot easily avoid representing text while posting to USENET, I
will not try. But I will offer a description of a real-world example:
<written on chalkboard> 7/3 </written on chalkboard>
You forgot to ask for EXACT representation, BTW.


Oh I see now what you meant was to stop asking a computer to represent
non-integer rational number.

That little funny probably worked with the brain-boxes who got via the
Maths/Physics degrees. Some of us got here the hard way. I didn't get it.
I thought you actually being serious and I was missing something
fundemental.

--
Anthony Jones - MVP ASP/ASP.NET


Add comment
Dr J R Stockton 22 August 2008 23:40:46 permanent link ]
 In comp.lang.javascrip­t message <Xns9B023D4525689ar­bpenyahoocom@69.16.1­8
5.247>, Fri, 22 Aug 2008 13:01:23, Adrienne Boswell <arbpen@yahoo.com>
posted:
The problem I have is that it doesn't round up, for instance in stead
of 0.95 i get 0.9499999999998.
Does anyone have any ideas how to fix this?

You could try reading the FAQ of comp.lang.javascrip­t, and/or my site.

A programmer should know that binary floats can represent few simple
decimal fractions exactly.

If your results are hoped to be in pounds, with a 2-digit decimal
fraction part, then calculate in pence and insert the point as part of
output formatting.

--
(c) John Stockton, nr London, UK. ?@merlyn.demon.co.u­k Turnpike v6.05 MIME.
Web <URL:http://www.mer­lyn.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)
Add comment
Anthony Jones 23 August 2008 16:58:50 permanent link ]
 "Dr J R Stockton" <jrs@merlyn.demon.c­o.uk> wrote in message
news:ytkla7eORyrIFw­Hf@invalid.uk.co.dem­on.merlyn.invalid...­
In comp.lang.javascrip­t message <Xns9B023D4525689ar­bpenyahoocom@69.16.1­8
5.247>, Fri, 22 Aug 2008 13:01:23, Adrienne Boswell <arbpen@yahoo.com>
posted:
The problem I have is that it doesn't round up, for instance in stead
of бё0.95 i get бё0.9499999999998.
Does anyone have any ideas how to fix this?
You could try reading the FAQ of comp.lang.javascrip­t, and/or my site.
A programmer should know that binary floats can represent few simple
decimal fractions exactly.
If your results are hoped to be in pounds, with a 2-digit decimal
fraction part, then calculate in pence and insert the point as part of
output formatting.


The floating point type works sufficiently for most reasonable figures such
as in this case. It has to be understood that you need to be careful when
dealing with money since from a users perspective you can present inaccurate
figures due to rounding problems even when using integer math internally.

In the abscence of a decimal type, unless you demonstrate really good
reasons otherwise, stick with float and keep it simple. Dealing with
figures in the the ё10K region with simple percentage calculations will not
result in bad stuff happening. Especially if the customer likes to see how
things are calculated and the figures they see on screen need to add up.





--
Anthony Jones - MVP ASP/ASP.NET


Add comment
 

Add new comment

As:
Login:  Password:  
 
 
  
 
Пожалуйста, относитесь к собеседникам уважительно, не используйте нецензурные слова, не злоупотребляйте заглавными буквами, не публикуйте рекламу и объявления о купле/продаже, а также материалы нарушающие сетевой этикет или УК РФ.


QAIX > ASP web-programming > problem with javascript in asp not rounding up.. 23 August 2008 16:58:50

see also:
configure service name in RAC
Oracle DBA Job Opening in Boston
Desperately need an SQL query for the…
пройди тесты:
see also:
What is OPC drum?-Conditioning
Who supply the accessaries of toner…

  Copyright © 2001—2008 QAIX
Idea: Miсhael Monashev
Помощь и задать вопросы можно в сообществе support.qaix.com.
Сообщения об ошибках оставляем в сообществе bugs.qaix.com.
Предложения и комментарии пишем в сообществе suggest.qaix.com.
Информация для родителей.
Write us at:
If you would like to report an abuse of our service, such as a spam message, please .