Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: Rounding fraction values?

2 views
Skip to first unread message
Message has been deleted

Tom Cole

unread,
Feb 22, 2007, 2:00:48 PM2/22/07
to

Tuxedo wrote:
> Does anyone know how to round up fraction values in Javascript?
>
> I would like to modify a variable starting at 1 ending at 0 in 25
> iterations, using setInterval, updating the variable accordingly. In other
> words that should be 4% each step. If each interval runs every 50
> milliseconds it should take about 1.25 seconds to complete the cycle.
>
> interval = setInterval("change()",50);
>
> 1.00 <!- starting value
>
> 0.96 first iteration
> 0.92 second ...
> 0.88 third ..
> 0.84 etc.
> 0.80
> 0.76
> 0.72
> 0.68
> 0.64
> 0.60
> 0.56
> 0.52
> 0.48
> 0.44
> 0.40
> 0.36
> 0.32
> 0.28
> 0.24
> 0.20
> 0.16
> 0.12
> 0.08
> 0.04
> 0.00 <- end value and clearInterval(interval)
>
> However, except for the first iteration, simply subtracting 0.04 from each
> value will return nemeric values as follows:
>
> 0.96
> 0.9199999999999999
> 0.8799999999999999
> 0.8399999999999999
> 0.7999999999999998
> 0.7599999999999998
> 0.7199999999999998
> 0.6799999999999997
> 0.6399999999999997
> 0.5999999999999996
> 0.5599999999999996
> 0.5199999999999996
> 0.4799999999999996
> 0.4399999999999996
> 0.39999999999999963
> 0.35999999999999965
> 0.3199999999999997
> 0.2799999999999997
> 0.23999999999999969
> 0.19999999999999968
> 0.15999999999999967
> 0.11999999999999966
> 0.07999999999999965
> 0.039999999999999654
> -3.469446951953614e-16
>
> Any ideas? Thanks in advance!

I don't know if this is the perfect solution but have you tried using
something like value = ((value * 100) - 4) / 100 ?

Lee

unread,
Feb 22, 2007, 2:24:05 PM2/22/07
to
Tuxedo said:
>
>Does anyone know how to round up fraction values in Javascript?

>0.11999999999999966


>0.07999999999999965
>0.039999999999999654
>-3.469446951953614e-16
>
>Any ideas? Thanks in advance!

This newsgroup, like most technical groups, has a FAQ that should be read
before you ask questions.

The parts you might find particularly interesting are:

http://www.jibbering.com/faq/#FAQ4_6
http://www.jibbering.com/faq/#FAQ4_7

as well as the web pages that those entries refer to, such as:
http://www.merlyn.demon.co.uk/js-round.htm


--

VK

unread,
Feb 22, 2007, 2:30:21 PM2/22/07
to
On Feb 22, 8:15 pm, Tuxedo <tux...@mailinator.net> wrote:
> I would like to modify a variable starting at 1 ending at 0 in 25
> iterations, using setInterval, updating the variable accordingly.

So the procedure will consist of subtracting 0.04 from current values.
0.04 == 4/100 == 1/25 == non-diadic fraction
So neither minuend (after first cycle) nor subtrahend (from the
beginning) will not be represented exactly involving internal rounding
and precision loss on each cycle. With 25 cycles the task is way
beyond of IEEE-754 math capabilities - after all it was made for
"home" (PC) math, so you suppose to go easy on it ;-) That is not some
JavaScript-particular limitation, the same apply for any lightweight
PC environment no matter if it's C, C++, C#, Java etc.

Because no one of intermediary values seems fail on equipoint choice
("5 to 1 or 0" in decimal system) you may disregard toFixed rounding
algorithm difference on IE and other browsers so use result.toFixed(2)
after each iteration.

Overall see <http://www.jibbering.com/faq/index.html#FAQ4_6> and
discussions.

> If each interval runs every 50
> milliseconds it should take about 1.25 seconds to complete the cycle.

I wouldn't count on it too much. The smallest interval cannot be
smaller than one system tick which is from 10ms to 60ms depending on
OS - with exact IRQ treatment taken very freely for really small
values - I mean on the system level. This way the second sign after
comma is a dangerous bogus - it may make you think that the error
begins from the third sign only. Let's say "it should take lesser than
2 seconds to complete the cycle".

Dr J R Stockton

unread,
Feb 22, 2007, 3:09:41 PM2/22/07
to
In comp.lang.javascript message <erkkhj$7t8$00$1...@news.t-online.com>,
Thu, 22 Feb 2007 18:15:00, Tuxedo <tux...@mailinator.net> posted:

>
>I would like to modify a variable starting at 1 ending at 0 in 25
>iterations, using setInterval, updating the variable accordingly. In other
>words that should be 4% each step. If each interval runs every 50

>milliseconds it should take about 1.25 seconds to complete the cycle.


You should do as much as possible in integers, as in

for (J=100 ; J>=0 ; J -= 4) { X = J/100 // not J*0.01
... // using X
}

For an understanding of numerical accuracy in javascript, see FAQ 4.7,
IEEE 754, and <URL:http://www.merlyn.demon.co.uk/js-maths.htm>, etc.

It's a good idea to read the newsgroup and its FAQ. See below.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 IE 6
news:comp.lang.javascript FAQ <URL:http://www.jibbering.com/faq/index.html>.
<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.

Message has been deleted
Message has been deleted
Message has been deleted
Message has been deleted

Richard Formby

unread,
Feb 23, 2007, 7:53:56 AM2/23/07
to
VK wrote:

a load of crap

Richard Cornford

unread,
Feb 23, 2007, 8:06:40 AM2/23/07
to
On Feb 22, 5:15 pm, Tuxedo <tux...@mailinator.net> wrote:
> Does anyone know how to round up fraction values in Javascript?
>
> I would like to modify a variable starting at 1 ending at 0 in 25
> iterations, using setInterval, updating the variable accordingly. In other
> words that should be 4% each step. If each interval runs every 50
> milliseconds it should take about 1.25 seconds to complete the cycle.
>
> interval = setInterval("change()",50);
>
> 1.00 <!- starting value
>
> 0.96 first iteration
> 0.92 second ...
> 0.88 third ..
> 0.84 etc.
<snip>

> 0.04
> 0.00 <- end value and clearInterval(interval)
>
> However, except for the first iteration, simply subtracting 0.04
> from each value will return nemeric values as follows:
>
> 0.96
> 0.9199999999999999
<snip>

> 0.039999999999999654
> -3.469446951953614e-16
>
> Any ideas? Thanks in advance!

The thing that you have not explained is why. You are trying to
achieve something, and the fact that what you are trying to achieve
will not work the way you are trying it does not mean that it cannot
be achieved in some other way.

Richard.

VK

unread,
Feb 23, 2007, 11:15:20 AM2/23/07
to
On Feb 23, 3:53 pm, "Richard Formby" <newsgro...@barefile.com.au>
wrote:

> VK wrote:
>
> a load of crap

Poor child,
which one of your darling illusions did I break? I cannot change the
world but at least I could bring some addressed consolations for you.

Randy Webb

unread,
Feb 23, 2007, 12:01:41 PM2/23/07
to
VK said the following on 2/23/2007 11:15 AM:

> On Feb 23, 3:53 pm, "Richard Formby" <newsgro...@barefile.com.au>
> wrote:
>> VK wrote:
>>
>> a load of crap
>
> Poor child,
> which one of your darling illusions did I break?

The illusion that you had an IQ above 10 would be a start.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/

VK

unread,
Feb 23, 2007, 1:10:52 PM2/23/07
to
On Feb 23, 2:37 am, Tuxedo <tux...@mailinator.net> wrote:
> I realise processing time will increase the calculation somewhat, but using
> setInterval should at least come a bit closer to target than if using
> setTimeout for example.

Two wrong assumptions in here:

1) the lateness of setTimeout/setInterval is rarely affected by the
complexity of calculations, at least definitely not in your case. I
cannot imagine an environment where calculating 1-0.04 = ? would take
50,000,000 or more processor cycles (taking 1GHz processor for the
start and 50ms as timeframe).
The problem is not when the process is ended: the problem is when the
process is started. setTimeout/setInterval are working on IRQ
(Interruption ReQuest) principles where everything is based on request
priority. When the system gets several different requests at one time,
it decides by their priorities what to proceed with and what to put on
hold till the next tick. setTimeout/setInterval IRQs from javascript
engine have the lowest priority. So every time the system has a
request to say move your DIV 1px right and anything else more
important to do (refresh screen, close file, handle swap file etc.
etc.) your IRQ is put on hold - because unlike other tasks this one
doesn't menace the system stability.

2) setTimeout and setInterval have the same IRQ priority, no any
advantages. The danger of setInterval is that with persistent lateness
you can get "on hold queue" growing and growing with many undesirable
effects. This is why I would never use setInterval for anything except
some simple operations with predictable execution time, like some
simple clock on the screen.

Netscape 4.0 and inherited by Gecko-based browsers do send extra
argument on timed call indicating lateness of the timeout in
milliseconds. It is called "lateness" but in fact IRQ can be processed
earlier as well if the system has some time left in the current tick
so do not waste it. This is why I said "taken very freely". So the
proper term would be "timeout delta value".

Some code to play with if still interested (Firefox or other Gecko-
based browser needed). It displays
processed number | timeout delta


<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script>
var num = 1;

var out = null;

function init() {
out = document.getElementById('output');
counter();
}

function counter() {
out.appendChild(document.createElement('li')).
appendChild(document.createTextNode(num.toFixed(2).
concat(' | ', arguments[0])));
if (num >= 0.04) {
num = (num-0.04);
window.setTimeout(counter, 50);
}
}

window.onload = init;
</script>
</head>

<body>
<ol id="output">
</ol>
</body>
</html>

VK

unread,
Feb 23, 2007, 1:26:09 PM2/23/07
to
On Feb 23, 2:37 am, Tuxedo <tux...@mailinator.net> wrote:
> Thanks for all other comments

This is what I forgot to mention the first time. That is just a
suggestion: If one makes a new post in hope to get some responses then
X-No-Archive header is a rather bad idea. I understand that some
people may be overly shy :-) or considering their questions as of too
low of relevance. Still X-No-Archive header should be used only in
particular circumstances like say announcements of dated events and
advertisement. Otherwise on news servers with X-No-Archive support
(Google archiver is one of them) it creates broken threads "coming
from nowhere" or with responses addressed to "nowhere".

Dr J R Stockton

unread,
Feb 23, 2007, 8:13:29 AM2/23/07
to
In comp.lang.javascript message <erkqk...@drn.newsguy.com>, Thu, 22
Feb 2007 11:24:05, Lee <REM0VElb...@cox.net> posted:
>Tuxedo said:

>>Does anyone know how to round up fraction values in Javascript?

>This newsgroup, like most technical groups, has a FAQ that should be read


>before you ask questions.
>
>The parts you might find particularly interesting are:

>as well as the web pages that those entries refer to, such as:
>http://www.merlyn.demon.co.uk/js-round.htm

Strictly, what you write is correct. But not in detail helpful,
since fundamentally he should not be using rounding, and should be
reading js-maths.htm

Dr J R Stockton

unread,
Feb 23, 2007, 3:52:19 PM2/23/07
to
In comp.lang.javascript message <1172254249.0...@t69g2000cwt.go
oglegroups.com>, Fri, 23 Feb 2007 10:10:52, VK <school...@yahoo.com>
posted:

>1) the lateness of setTimeout/setInterval is rarely affected by the
>complexity of calculations, at least definitely not in your case. I
>cannot imagine an environment where calculating 1-0.04 = ? would take
>50,000,000 or more processor cycles (taking 1GHz processor for the
>start and 50ms as timeframe).
>The problem is not when the process is ended: the problem is when the
>process is started. setTimeout/setInterval are working on IRQ
>(Interruption ReQuest) principles where everything is based on request
>priority. When the system gets several different requests at one time,
>it decides by their priorities what to proceed with and what to put on
>hold till the next tick.


That would be a ludicrous way to build a system; I am surprised that
even you might suggest it.

The sensible way is to have a queue of events, ordered by the time when
it is desired that they should occur.

When a tick occurs, the events for that tick are started or performed in
turn, in priority order (they should probably be listed in that order,
for swift dispatch). Hopefully, all will be dealt with before the next
tick; if not, a higher-priority one which has become due will interrupt
a lower-priority one.

The system must have a policy to handle the case where the average
amount of work demanded exceeds what can be done in the time available.

It's a good idea to read the newsgroup and its FAQ. See below.

--

Message has been deleted

Tuxedo

unread,
Feb 25, 2007, 7:03:47 AM2/25/07
to
VK wrote:

[..]

> X-No-Archive header is a rather bad idea. I understand that some

This is or was a default setting of the newsreader used, which I was
unaware of as I do not keep full headers on display.

[...]

> advertisement. Otherwise on news servers with X-No-Archive support

Surprisingly this newsgroups, as many others, appears resistant to
spamvertising. I doubt any spammers would use the X-No-Archive for good
measure.

> (Google archiver is one of them) it creates broken threads "coming
> from nowhere" or with responses addressed to "nowhere".

True, this can make a thread incomprehensible.

Tuxedo

unread,
Feb 25, 2007, 7:08:37 AM2/25/07
to
Randy Webb wrote:

[..]

> The illusion that you had an IQ above 10 would be a start.

I'm not sure what the bickering is all about!? I thought this was a
civilized NG ;-)

Tuxedo

unread,
Feb 25, 2007, 8:11:29 AM2/25/07
to
Richard Cornford wrote:

[..]

> be achieved in some other way.

It is true that I did not point out "why" in my original post.

The original purpose was simply to generate a sequence of legal opacity
values with a loop. Later however I realized that it probably makes little
or no difference whether fractional or rounded values are used for this, so
the question became more for a point than for a purpose, i.e. how to output
the rounded numbers by some simple math formula, thus I ommited the
purpose. By the various responses above I also realized that this may be
easier said than done, and that I have many faq's to read on this subject.
And as you say, there probably are other ways of achieving the same.

Tuxedo

unread,
Feb 25, 2007, 8:54:21 AM2/25/07
to
Tom Cole wrote:

[...]

> I don't know if this is the perfect solution but have you tried using
> something like value = ((value * 100) - 4) / 100 ?

With the small addition of Math.floor, the following returns the desired
and unfractioned list of values in this example:

value = 1.0

while (value >= 0.04){
value = (Math.floor(value * 100) - 4) / 100
document.write(value +'<br>')
}

writes:

0.96
0.92
0.88
0.84
0.8
0.76
0.72
0.68
0.64
0.6
0.56
0.52
0.48
0.44
0.4
0.36
0.32
0.28
0.24
0.2
0.16
0.12
0.08
0.04
0

Dr J R Stockton

unread,
Feb 25, 2007, 9:37:37 AM2/25/07
to
In comp.lang.javascript message <errvmr$f8j$03$2...@news.t-online.com>,
Sun, 25 Feb 2007 13:08:37, Tuxedo <tux...@mailinator.net> posted:

By sufficiently reading the newsgroup before posting, you could have
discovered in advance what a poster needs to do in order to appear
civilised.

--
(c) John Stockton, Surrey, UK. ???@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.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.

VK

unread,
Feb 25, 2007, 2:42:05 PM2/25/07
to
> That would be a ludicrous way to build a system; I am surprised that
> even you might suggest it.
>
> The sensible way is to have a queue of events, ordered by the time when
> it is desired that they should occur.
<snip>

I truly missed the need of this explanation unless "even you"
insertion was the only purpose ;-)
Both explanations (mine and yours) is a profanation of the real
mechanics anyway. Yours adds a bit of more details atop, but IMO it's
the case when "either say everything or limit by a basic hint". The
exact mechanics with IRQ, queues, dispatchers etc. cannot be described
in one or two paragraphs of plain text, so why to try?
My intention was to hint users that setTimeout(doSomething, 50) is
_not_ running in 50ms unless by some really strange coincidence.
On a bigger scale I tried to hint that any PC with OS for PS installed
is not a real-time system and that by switching from JavaScript to say
C++ or Java your PC doesn't become a strategic emulator on Cray
clusters :-)

Tuxedo

unread,
Feb 25, 2007, 3:29:05 PM2/25/07
to
Dr J R Stockton wrote:

[...]

> By sufficiently reading the newsgroup before posting, you could have
> discovered in advance what a poster needs to do in order to appear
> civilised.
>

Sorry I don't follow you. Please feel free to elaborate for those who don't.

VK

unread,
Feb 25, 2007, 4:15:31 PM2/25/07
to
> > By sufficiently reading the newsgroup before posting, you could have
> > discovered in advance what a poster needs to do in order to appear
> > civilised.
>
> Sorry I don't follow you. Please feel free to elaborate for those who don't.

IMHO the keyword here is "aristocratic netiquette".

"Now, an aristocrat, you know, the world over, has no human
sympathies, beyond a certain line in society. ... What would be
hardship and distress and injustice in his own class, is a cool matter
of course in another one."
Harriet Beecher Stowe

:-)

Dr J R Stockton

unread,
Feb 25, 2007, 3:51:04 PM2/25/07
to
In comp.lang.javascript message <ers5t2$rd9$03$1...@news.t-online.com>,
Sun, 25 Feb 2007 14:54:21, Tuxedo <tux...@mailinator.net> posted:

>
>With the small addition of Math.floor, the following returns the desired
>and unfractioned list of values in this example:
>
>value = 1.0
>
>while (value >= 0.04){
>value = (Math.floor(value * 100) - 4) / 100
>document.write(value +'<br>')
>}

There you are assuming, which happens to be true in this case, that
value*100-4 will never be below the nominal integer value. If the 4
is changed to 3, there is an error at about 0.55; if to 7, at 0.25 &
0.55. The method is unsound. Understand IEEE-754 and FAQ 4.7.


value = 100
while (value >= 4) {
value = value - 4
document.write(value/100 +'<br>')
}

writes the right numbers reliably.


for (value = 96 ; value >= 0 ; value -= 4 )
document.write(value/100 +'<br>')

is probably how most experienced people would do it, except when speed
is crucial.


<FAQENTRY> The page linked to from FAQ 4.7 is neither well-written nor
accurate. The link should be supplemented by one to a well-written and
accurate page. Suggestions?

Seek via
<http://www.efg2.com/Lab/Library/Delphi/MathInfo/#FloatingPointNumbers>
<http://web.archive.org/web/20040406121124/http://www.mindspring.com/~ef
d/acc101.htm>
<http://docs.sun.com/source/806-3568/ncg_goldberg.html> (maybe not best
URL for it?)
Google "John Herbster" with Delphi & not Dental.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.


Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.

For news:borland.*, use their server newsgroups.borland.com ; but first read
Guidelines <URL:http://www.borland.com/newsgroups/guide.html> ff. with care.

Dr J R Stockton

unread,
Feb 26, 2007, 12:09:14 PM2/26/07
to
In comp.lang.javascript message <1172432525.3...@z35g2000cwz.go
oglegroups.com>, Sun, 25 Feb 2007 11:42:05, VK <school...@yahoo.com>
posted:

>> That would be a ludicrous way to build a system; I am surprised that
>> even you might suggest it.
>>
>> The sensible way is to have a queue of events, ordered by the time when
>> it is desired that they should occur.
><snip>
>
>I truly missed the need of this explanation unless "even you"
>insertion was the only purpose ;-)

It was because there was a glaring error in what you wrote, one which it
would be a pity to have anyone other than you believe.

--
(c) John Stockton, Surrey, UK. ???@merlyn.demon.co.uk Turnpike v6.05 MIME.


Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.

0 new messages