473,796 Members | 2,560 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Round off

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

Apr 4 '06
36 5914
el*********@ele ctrician.com said on 06/04/2006 2:05 PM AEST:
// Roundoff routine for 2 decimal places
// used someplaces.

function round(x) {
return Math.round(x*10 0)/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.
--
Rob
Group FAQ: <URL:http://www.jibbering.c om/FAQ>
Apr 6 '06 #11
> 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.c om/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.


Apr 6 '06 #12
Hal Rosser said on 06/04/2006 2:53 PM AEST:
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.c om/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.


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.03 5*100)/100 gives 1.03
but Math.round(2.03 5*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.

--
Rob
Group FAQ: <URL:http://www.jibbering.c om/FAQ>
Apr 6 '06 #13

"Phat G5 (G3)" <no****@noone.c om> schrieb im Newsbeitrag
news:C05842D8.3 3E67%no****@noo ne.com...
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((num ber+.5) * places) / places;
}

Not tested, but should work.
Apr 6 '06 #14
Zif
Gernot Frisch wrote:
"Phat G5 (G3)" <no****@noone.c om> schrieb im Newsbeitrag
news:C05842D8.3 3E67%no****@noo ne.com...
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));


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.465794806 718. Always.

return Math.floor((num ber+.5) * places) / places;
Here you arbitrarily add 0.5, multiply by a constant (22026.46579480 6718),
'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.9588738752886 79.

Is that any use what so ever to the OP?
--
Zif
Apr 6 '06 #15
"Gernot Frisch" <Me@Privacy.net > writes:

[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((num ber+.5) * places) / places;
The .5 should be just before flooring, so:

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


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

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Apr 6 '06 #16
JRS: In article <_2************ @bignews8.bells outh.net>, dated Wed, 5
Apr 2006 21:25:28 remote, seen in news:comp.lang. javascript, Hal Rosser
<hm******@bells outh.net> posted :

"Phat G5 (G3)" <no****@noone.c om> wrote in message
news:C05842D8. 33E67%no****@no one.com...
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)


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.writel n(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.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Apr 6 '06 #17

"Dr John Stockton" <jr*@merlyn.dem on.co.uk> wrote in message
news:CS******** ******@merlyn.d emon.co.uk...
JRS: In article <_2************ @bignews8.bells outh.net>, 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.writel n(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.
Apr 7 '06 #18
Hal Rosser said the following on 4/6/2006 10:59 PM:
"Dr John Stockton" <jr*@merlyn.dem on.co.uk> wrote in message
news:CS******** ******@merlyn.d emon.co.uk...
JRS: In article <_2************ @bignews8.bells outh.net>, 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.
***


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.writel n(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.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Apr 7 '06 #19
In article <2x************ **@bignews8.bel lsouth.net>, Hal Rosser
<hm******@bells outh.net> writes

<snip>
******
The OP asked about rounding a number to 2 decimals - not about converting it
to a string.
***

<snip>

The most reliable way to do decimal rounding is to operate on the
decimal representation of the number. In javascript this means you have
to start by translating the internal binary representation into a
string. (At present. Microsoft wanted numbers to be decimal-coded. I
don't know if they still do.)

This is probably what JohnS meant. Then again, perhaps not. It's not
always easy to work out what he means when he's operating in sarcastic
teacher mode.

Actually, the OP didn't say if he wants decimal rounding, or hexadecimal
rounding, or duodecimal rounding, or ternary rounding, or binary
rounding to two places. We are all guessing he meant decimal as that's
what most people want to display to their end users.

John
--
John Harris
Apr 7 '06 #20

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

Similar topics

2
3133
by: Matias Silva | last post by:
Can anybody tell me why I am getting rounding errors using the ROUND function. 3.7125 rounds to 3.70 when I use the following: TRUNCATE(ROUND(units_pay_amount * fees_amount, 2),2))) The correct value should be 3.71 I could round to the 3rd decimal place ROUND(X,3) and that would round it correctly to 3.71 but that would mean I would have to change the ROUND function in another
6
18675
by: Penguin | last post by:
At some long ago time Steve Jorgensen answered thus: Subject: Re: How can I round a time? Newsgroups: comp.databases.ms-access Date: 1998/12/11 Access represents a date internally as a double and will convert between date/time and double automatically. The double value Access (or VB) creates is based on 1 day = 1.0 and the fractional part represents a
17
5660
by: nomenklatura | last post by:
Hi, System.Math.Round function is confused me. for example i want to round 3.245 in with decimal symbol Result should be = 3.25 When i try to this in vb: A = 3.245 X = Round(A, 2) then x=3.24 , result is is false
9
7386
by: Ronald W. Roberts | last post by:
I'm having a problem understanding the Round function. Below are quotes from two books on VB.NET. The first book shows examples with one argument and how it rounds. The second book something different. Programming Microsoft Windows with Microsoft Visual Basic.NET "The Round method with a single argument return the whole number nearest to the argument. If the argument to Round is midway between two whole numbers,
4
7255
by: Fuzzydave | last post by:
I have been using a round command in a few places to round a value to zero decimal places using the following format, round('+value+', 0) but this consistantly returns the rounded result of the value to one decimal place with a zero EG:
10
16037
by: David Coleman | last post by:
I am running VS 2003 and have applied SP1. (On WinXP SP2, .Net 1.1) In the Command Window I get the following ? Math.Round(0.715, 2) 0.72 ? Math.Round(0.725, 2) 0.72 ? Math.Round(0.735, 2) 0.74
7
4477
by: kkmigas | last post by:
Can some one explain if this can be fixed using php.ini settings ? echo "round 20.545 -".round(20.545,2)."<br>"; echo "round 20.555 -".round(20.555,2)."<br>"; echo "number_format 20.545 -".number_format(20.545, 2, ',', '.')."<br>"; echo "number_format 20.555 -".number_format(20.555, 2, ',', '.')."<br>"; PHP Version 4.3.0 / FreeBSD
3
1834
by: Krishna.K.1900 | last post by:
Does round() always perfectly return the output expected or are there some artifacts which don't allow perfect functionality Using python 2.5: 12.23 12.234 12.199999999999999 but was expecting 12.2
4
10900
by: =?Utf-8?B?UmVuZQ==?= | last post by:
Hello everyone I have a problem with Math.Round, it´s ocurring some strange: Math.Round(12.985) = 12.98, it´s wrong. It should be: 12.99 Why?? What is the problem? Help ME !!!!
9
6558
by: josh logan | last post by:
Hello, I need a round function that _always_ rounds to the higher integer if the argument is equidistant between two integers. In Python 3.0, this is not the advertised behavior of the built-in function round() as seen below: 0 2 2
0
9684
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10459
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10182
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10017
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7552
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6793
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5445
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4120
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3734
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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

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