Round off

P

Phat G5 (G3)

Has anyone found a reliable way to force JS to round to a specific number of
places? Every time I try I get different results. For example, I'd need to
round 3.4589 to 2 places. What is the most reliable way to do it?

Thanks

-S
 
R

Randy Webb

Phat G5 (G3) said the following on 4/4/2006 6:35 PM:
Has anyone found a reliable way to force JS to round to a specific number of
places?
Yes.

Every time I try I get different results.

Then you aren't doing it right.
For example, I'd need to round 3.4589 to 2 places.

Hmmm. I seem to recall something in the group FAQ about rounding to 2
places.
What is the most reliable way to do it?

Most reliable? Post in Usenet and ask how to do it to have someone point
you to the FAQ of the group you post it to.
 
D

Dr John Stockton

JRS: In article <C05842D8.33E67%[email protected]>, dated Tue, 4 Apr
2006 15:35:52 remote, seen in Phat G5 (G3)
Has anyone found a reliable way to force JS to round to a specific number of
places? Every time I try I get different results. For example, I'd need to
round 3.4589 to 2 places. What is the most reliable way to do it?

By reading the newsgroup FAQ before posting, and finding, IIRC, section
4.6 therein.

Your "most reliable" is a pointless term; either a method is reliable
(perhaps within stated limits) or it is wrong.

Remember the "Banker's Rounding" question, and the limitations on which
exact values a Number can take.

Of course, if your 3.4589 is a String, a different approach should be
considered.
 
H

Hal Rosser

Phat G5 (G3) said:
Has anyone found a reliable way to force JS to round to a specific number of
places? Every time I try I get different results. For example, I'd need to
round 3.4589 to 2 places. What is the most reliable way to do it?

Some folks find it satisfactory to:
multiply the number by 100, then round it , then divide that by 100.
Some folks rather hassle a person over a well-meant question -
or a well-meant answer - like this.
( here it comes, I'm sure)
 
T

Thomas 'PointedEars' Lahn

Hal said:
"Phat G5 (G3)" [...] wrote [...]
Has anyone found a reliable way to force JS to round to a specific number
of places? Every time I try I get different results. For example, I'd
need to round 3.4589 to 2 places. What is the most reliable way to do it?

Some folks find it satisfactory to:
multiply the number by 100, then round it , then divide that by 100.
Some folks rather hassle a person over a well-meant question -
or a well-meant answer - like this.
( here it comes, I'm sure)

Your well-meant answer is simply bad advice. The FAQ (which is an acronym
for Frequently Asked Questions -- remember?) tells why, and understanding
how numeric values are stored in ECMAScript implementations, which we
discussed at great length and in great detail not too long ago, also does.

I got the impression that this newsgroup is dedicated to giving the best
advice possible, so do not be surprised if you get bashed when you post
(such) clueless nonsense.


PointedEars
 
H

Hal Rosser

Hal Rosser said:
number

Some folks find it satisfactory to:
multiply the number by 100, then round it , then divide that by 100.
Some folks rather hassle a person over a well-meant question -
or a well-meant answer - like this.
( here it comes, I'm sure)

I'm not sure - but it looks like someone is saying its incorrect to round to
2 decimals with code
like this;
var num = 3.4589; // ***( number to be rounded to 2 decimals)
num = num * 100; //*** (Multiply the number by 100) num is now 345.89
num = Math.round(num); //*** (Then round it) num is now 346
num = num/100; // *** (then divide that number by 100) num is now 3.46
-- but I have seen the exact code in text books used in many schools.
Why is my (well-meaning) answer wrong ?
or should OP jump through 20 hoops before getting a straight answer from a
couple of mean-spirited ego hounds who think this group is the ultimate
source for javascript.
**never-mind**
---OP --- do what they say
 
R

RobG

Hal Rosser said on 06/04/2006 12:09 PM AEST:
The FAQ provides a solution and explanation of why other methods are
faulty, hence other posters referenced the FAQ rather than attempt to
parrot or paraphrase it.

I'm not sure - but it looks like someone is saying its incorrect to round to
2 decimals with code
like this;

Yes, they are.

var num = 3.4589; // ***( number to be rounded to 2 decimals)
num = num * 100; //*** (Multiply the number by 100) num is now 345.89
num = Math.round(num); //*** (Then round it) num is now 346
num = num/100; // *** (then divide that number by 100) num is now 3.46
-- but I have seen the exact code in text books used in many schools.

The fact that something is written in a book does not make it good
advice. Some would say that any advice found in some books is almost
certainly wrong. ;-)

Why is my (well-meaning) answer wrong ?

The reason why it is wrong is explained in the FAQ - your proposed
solution does not always give the right answer. The short answer is
because JavaScript numbers can't represent all decimal values exactly,
depending on them to do so will fail some of the time.

e.g.

12.024999999999999 -> 12.02 as expected
12.0249999999999999 -> 12.03 ?

or should OP jump through 20 hoops before getting a straight answer from a
couple of mean-spirited ego hounds who think this group is the ultimate
source for javascript.
**never-mind**
---OP --- do what they say

Read FAQ 4.6, it is rather concise but if studied it will all become
apparent. Also read 4.7, which helps to explain why the *100/100
method doesn't work consistently.

<URL:http://www.jibbering.com/FAQ/#FAQ4_6>


If you have any specific questions, ask. Do not mind that some
responses are curt or abrupt - such is life.

Search the archives for questions on rounding - you may be surprised by
totally unrelated gems you discover. :)

Or use:

<URL:http://www.merlyn.demon.co.uk/js-round.htm>
 
E

electrician

// Roundoff routine for 2 decimal places
// used someplaces.

function round(x) {
return Math.round(x*100)/100;
}

Been using it for years in my raceway fill calculator at
http://www.electrician2.com/
And never had a complaint.
 
E

electrician

<If you have any specific questions, ask. Do not mind that some
responses are curt or abrupt - such is life.


Search the archives for questions on rounding - you may be surprised by

totally unrelated gems you discover. :) >

You are so anal your head is coming out of your ass. Just thought I
would let you know before you are seen in public.
 
R

RobG

(e-mail address removed) said on 06/04/2006 2:09 PM AEST:
<If you have any specific questions, ask. Do not mind that some
responses are curt or abrupt - such is life.


Search the archives for questions on rounding - you may be surprised by

totally unrelated gems you discover. :) >

You are so anal your head is coming out of your ass. Just thought I
would let you know before you are seen in public.

You're a very funny fellow. :p

Funniest thing is not only don't you understand why you are wrong, but
you refuse to learn. You've posted incorrect responses before and had
the errors pointed out to you, yet you persist in offering bad advice.

Troll-on.
 
R

RobG

(e-mail address removed) said on 06/04/2006 2:05 PM AEST:
// Roundoff routine for 2 decimal places
// used someplaces.

function round(x) {
return Math.round(x*100)/100;
}

Been using it for years in my raceway fill calculator at
http://www.electrician2.com/
And never had a complaint.

Ah, so that's why you include the comment:

// Code roundoff method may not be consistant!
// There may be other hairline problems not found yet!!

Care to explain to the OP why you figure it's not worth pointing out
that you don't know the limitations of the function you propose?

The only way anyone is going to complain about your calculator is if
they fully test it to discover the errors or it causes a catastrophic
failure.

Given the complexity of doing so, it is unlikely anyone will attempt the
former, they trust you to have done it. And given the nature of most
electrical products, there is sufficient safety margin to prevent the
second provided your errors don't encroach too far.

But that does not make your rounding algorithm a good solution,
particularly when its shortcomings, and a simple and reliable
alternative, have been pointed out to you.
 
H

Hal Rosser

Read FAQ 4.6, it is rather concise but if studied it will all become
apparent. Also read 4.7, which helps to explain why the *100/100
method doesn't work consistently.

<URL:http://www.jibbering.com/FAQ/#FAQ4_6>


If you have any specific questions, ask. Do not mind that some
responses are curt or abrupt - such is life.

Ok, I read that FAQ 4.6
The code in that section is a marvelous display of someone's mastery of
javascript. I applaud the author.
The code, however, is missing comments (documentation) explaining what the
code is doing, and what the args represent. Someone looking for help (ie: a
beginner - or a programmer of lesser experience in javascript- like myself)
would likely come away from FAQ 4.2 with a sense of confusion. You have to
admit, someone else's undocumented code is sometimes difficult to follow.
I also followed the first link listed in FAQ 4.2 to look for clearer
explanations on the art of rounding a number like 3.4589 to 2 decimals.
Then I followed the link (in FAQ 4.2) to a section of that page (General
Rounding section) and guess what!!! -
Look at the 3rd example in the "General Rounding" section of that link:
http://www.merlyn.demon.co.uk/js-round.htm#Gen
It sure looks like they multiplied by 100, then rounded it, then divided by
100 - doesn't it?
The circle is complete, and the wild goose we were sent to chasing suddenly
vanishes.
w3schools.com and devguru.com are not entirely without merit after all.
 
R

RobG

Hal Rosser said on 06/04/2006 2:53 PM AEST:
Ok, I read that FAQ 4.6
The code in that section is a marvelous display of someone's mastery of
javascript. I applaud the author.
The code, however, is missing comments (documentation) explaining what the
code is doing, and what the args represent. Someone looking for help (ie: a
beginner - or a programmer of lesser experience in javascript- like myself)
would likely come away from FAQ 4.2 with a sense of confusion. You have to
admit, someone else's undocumented code is sometimes difficult to follow.

Yes, completely, both in general and this particular case.

I also followed the first link listed in FAQ 4.2 to look for clearer
explanations on the art of rounding a number like 3.4589 to 2 decimals.
Then I followed the link (in FAQ 4.2) to a section of that page (General
Rounding section) and guess what!!! -
Look at the 3rd example in the "General Rounding" section of that link:
http://www.merlyn.demon.co.uk/js-round.htm#Gen
It sure looks like they multiplied by 100, then rounded it, then divided by
100 - doesn't it?

Yes, but the preceding text notes that[1]:

Math.round(1.035*100)/100 gives 1.03
but Math.round(2.035*100)/100 gives 2.04


Hopefully my formatting makes the error obvious.

This may seem trivial, however originally the difference between the two
numbers was 1.00, now it's 1.01. Depending on how that is used, a test
may pass or fail that should not have.

The circle is complete, and the wild goose we were sent to chasing suddenly
vanishes.
w3schools.com and devguru.com are not entirely without merit after all.

I do not like DevGuru at all, avoid it. I am less inclined to recommend
w3schools each time I visit. Both sites claim to be more than they are,
they are misleading their audience if they propose a flawed method of
rounding and do not point out the errors. What other errors are waiting
to be discovered? These sites are targeted at novices who know no
better, yet teach bad habits and fautly algorithms.

I understand criticism of JRS's coding style, IMHO it is unreasonably
concise, particularly when it is aimed at education. But for all his
faults, he is nearly always factually correct in regard to the topics
discussed at www.merlyn.demon.co.uk/js*.



1. To JRS, if lurking, note the addition of '/100' in the quoted text.
 
G

Gernot Frisch

Phat G5 (G3) said:
Has anyone found a reliable way to force JS to round to a specific
number of
places? Every time I try I get different results. For example, I'd
need to
round 3.4589 to 2 places. What is the most reliable way to do it?



Document.Write(Round(3.4589, 2));
function Round(number, places)
{
places = Math.exp(10, places);
return Math.floor((number+.5) * places) / places;
}

Not tested, but should work.
 
Z

Zif

Gernot said:
Document.Write(Round(3.4589, 2));

Is that supposed to be document.write()?
function Round(number, places)
{
places = Math.exp(10, places);

Math.exp(x) takes one argument, not two. The second argument will be
ignored. You are setting places to the value of Math.exp(10) -
approximately 22026.465794806718. Always.

return Math.floor((number+.5) * places) / places;

Here you arbitrarily add 0.5, multiply by a constant (22026.465794806718),
'floor' the result, then divide by the same constant. How is that going to
guarantee a reliable rounding function?

}

Not tested, but should work.

Had you tested it you'd find that it doesn't 'work'. Given 3.4589, your
Round function returns 3.958873875288679.

Is that any use what so ever to the OP?
 
L

Lasse Reichstein Nielsen

[round to two places]
Document.Write(Round(3.4589, 2));
function Round(number, places)
{
places = Math.exp(10, places);

should be:
places = Math.pow(10, places)
(for readability reasons, I would create a new variable instead
of reusing the parameter).
return Math.floor((number+.5) * places) / places;

The .5 should be just before flooring, so:

return Math.floor((number * places) + 0.5) / places;
Not tested, but should work.

No better than
return Math.round(number * places)/places;
which has been debunked elsewhere in the thread.

/L
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Wed, 5
Apr 2006 21:25:28 remote, seen in Hal Rosser
Some folks find it satisfactory to:
multiply the number by 100, then round it , then divide that by 100.
Some folks rather hassle a person over a well-meant question -
or a well-meant answer - like this.
( here it comes, I'm sure)

Perhaps you could ask your mathematics teachers about the conceptual
difference between rounding to a multiple of 0.01 giving a Number, and
rounding to two decimal places which necessarily gives a String.

===========

In my system, somewhat to my surprise, Math.pow(10, N) is faster than
Number("1e"+N), and is sufficiently accurate[*] ; unless I hear that the
contrary is generally true, I'll change my pages.

[*] for (j=0; j<40; j++) document.writeln(j, " ", +("1E"+j), " ",
t=Math.pow(10, j), " ", t%1, "<br>")
My results for 23 & 29 need some more thought.

FAQ 4.6 can be correspondingly changed.
 
H

Hal Rosser

Dr John Stockton said:
JRS: In article <[email protected]>, dated Wed, 5
Perhaps you could ask your mathematics teachers about the conceptual
difference between rounding to a multiple of 0.01 giving a Number, and
rounding to two decimal places which necessarily gives a String.
******
The OP asked about rounding a number to 2 decimals - not about converting it
to a string.
***
===========

In my system, somewhat to my surprise, Math.pow(10, N) is faster than
Number("1e"+N), and is sufficiently accurate[*] ; unless I hear that the
contrary is generally true, I'll change my pages.

[*] for (j=0; j<40; j++) document.writeln(j, " ", +("1E"+j), " ",
t=Math.pow(10, j), " ", t%1, "<br>")
My results for 23 & 29 need some more thought.

FAQ 4.6 can be correspondingly changed.

I'm sure that code is very clever and correct.
It is, however just so mush gibberish to someone who's trying to learn
something.
The code has no comments (documentation) to explain what the args represent
or what the code is doing, or which function is to be called or in what
manner or what order.
It would be nice if someone would take a look at the FAQs and add comments
where they would help a newbie.
The FAQs now appears to be a place where people who already know javascript
are showing off their proficiency in the language to each other.
This is meant to be constructive, so I hope its taken as such.
 
R

Randy Webb

Hal Rosser said the following on 4/6/2006 10:59 PM:
******
The OP asked about rounding a number to 2 decimals - not about converting it
to a string.
***

And the best, reliable, method of rounding a number to 2 decimal places
is done by converting that number to a string and then doing string
manipulation.
===========

In my system, somewhat to my surprise, Math.pow(10, N) is faster than
Number("1e"+N), and is sufficiently accurate[*] ; unless I hear that the
contrary is generally true, I'll change my pages.

[*] for (j=0; j<40; j++) document.writeln(j, " ", +("1E"+j), " ",
t=Math.pow(10, j), " ", t%1, "<br>")
My results for 23 & 29 need some more thought.

FAQ 4.6 can be correspondingly changed.

I'm sure that code is very clever and correct.

It's irrelevant actually to the question at hand.
It is, however just so mush gibberish to someone who's trying to learn
something.

Most of John's code appears to be gibberish even to those that
understand it.
The code has no comments (documentation) to explain what the args represent
or what the code is doing, or which function is to be called or in what
manner or what order.
It would be nice if someone would take a look at the FAQs and add comments
where they would help a newbie.

Very true. It doesn't do a lot of good to say "Read the FAQ" if the FAQ
is not written with the novice/newbe in mind.
The FAQs now appears to be a place where people who already know javascript
are showing off their proficiency in the language to each other.

Not true.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top