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

"Phat G5 (G3)" <no****@noone.c om> wrote in message
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?

Thanks

-S


** Here's latest version thanks to John's code-testing services
** removed some superfluous code and fixed the 1-digit bug

//**args ->nnn = the number to round and yyy= the number of places
function roundyv3(nnn,yy y){
//** the multiplier to use
var multy = "1e"+yyy;//*same as Math.pow(10, yyy) ***
nnn+=""; //** coerce nnn to a String
//make sure there's a dot and something after it
if (nnn.indexOf(". ") < 0){
nnn += ".0";
}
//** adding zeroes after the dot makes it behave when rounding
nnn = nnn + "00000";
//** now rounding works - but removes the dot if a whole number ***
var strOut = String(Math.rou nd(nnn * multy) / multy);
//add back the decimal if rounding removed it and yyy > 0
if (strOut.indexOf (".") < 0 && yyy > 0) {
strOut+= ".0";
}
var placesInStrOut = strOut.length - strOut.indexOf( ".") - 1;
var zeroesNeeded = yyy - placesInStrOut;
var strZeroes = String(Math.pow (10, zeroesNeeded));
if (zeroesNeeded > 0) {
strOut += strZeroes.subst r(1);
}
return strOut;
}
Apr 11 '06 #31

"Dr John Stockton" <jr*@merlyn.dem on.co.uk> wrote in message
news:EQ******** ******@merlyn.d emon.co.uk...
JRS: In article <UV************ ****@bignews5.b ellsouth.net>, dated Sun,
9 Apr 2006 15:08:45 remote, seen in news:comp.lang. javascript, Hal
Rosser <hm******@bells outh.net> posted :
FAQ 4.6 deals with cases that your code does not attempt to deal with;
so you may not see the need for some of it. ***
OK... right - but its not documented and its confusing code
Your code provides no way to choose the representation of the sign; 4.6
does, by modifying Sign. ***
Don't see a need for it negatives have a minus sign, (You want to add
parentheses, or what, for negatives?)
The code in the FAQ provides a routine, Stretch, potentially useful
elsewhere. If it's not used elsewhere, that part of the job can easily
be done within StrU. *******
but it is uncommented ,obfuscated code
You blasted my code (in a previous post) for not indenting-- but look at the
code in FAQ4.6 hehe
The code in the FAQ adds leading zeroes if required. ***
(For rounding backwards ??) (When would that be required?)
The code in the FAQ also shows how to implement a .toFixed for Number. **
I disagree - it confuses the reader unless he doesn't need to read the FAQ
**
By the way, although I used to use the code in the FAQ, I now use code
developed from it. ***
I would be interested in seeing *documented* code you're now using.
****
If the input nnn is a small integer, your code extends it, changing its
value. Try, for example, roundyv2(1, 2), which gives "10". ***
Fixed that - good catch - I forgot to reinsert the dot after rounding (whole
numbers).
For what conditions do you think that your lines between my added //
marks actually do something useful, and what do they then achieve? ***
Removed that - another decent (and constructive) catch - thanks.
Is using Math.pow an *efficient* way of generating trailing zeroes, in
comparison with others, averaged over probable usage?

***
The second hand on my clock didn't move much when that code executed, but I
changed one instance to the "1e" + x method. Purity of code is a good cause
I guess though.

I fixed it and reposted. Thanks for testing.
I took a 'software testing' course - but you have a real knack for it.
Hal
Apr 11 '06 #32
In article <h%************ *****@bignews6. bellsouth.net>, Hal Rosser
<hm******@bells outh.net> writes

<snip>
** Here's latest version thanks to John's code-testing services
** removed some superfluous code and fixed the 1-digit bug

//**args ->nnn = the number to round and yyy= the number of places
function roundyv3(nnn,yy y)
/* Preconditions :
abs(nnn) < 2^52 or thereabouts (you don't test for 'e' or 'E')
abs(yyy) < 20 or so (any more is pointless)
*/
{
//** the multiplier to use
var multy = "1e"+yyy;//*same as Math.pow(10, yyy) ***
nnn+=""; //** coerce nnn to a String
//make sure there's a dot and something after it
if (nnn.indexOf(". ") < 0){
nnn += ".0";
}
//** adding zeroes after the dot makes it behave when rounding
nnn = nnn + "00000";
//** now rounding works - but removes the dot if a whole number ***
I don't see why you converted nnn into a string when the next thing you
do is convert it back into the original number.
var strOut = String(Math.rou nd(nnn * multy) / multy);
//add back the decimal if rounding removed it and yyy > 0
if (strOut.indexOf (".") < 0 && yyy > 0) {
strOut+= ".0";
}
var placesInStrOut = strOut.length - strOut.indexOf( ".") - 1;
var zeroesNeeded = yyy - placesInStrOut;
var strZeroes = String(Math.pow (10, zeroesNeeded));
if (zeroesNeeded > 0) {
strOut += strZeroes.subst r(1);
}
return strOut;
}


John
--
John Harris
Apr 11 '06 #33

"John G Harris" <jo**@nospam.de mon.co.uk> wrote in message
news:Z4******** ******@jgharris .demon.co.uk...
In article <h%************ *****@bignews6. bellsouth.net>, Hal Rosser
<hm******@bells outh.net> writes

<snip>
** Here's latest version thanks to John's code-testing services
** removed some superfluous code and fixed the 1-digit bug

//**args ->nnn = the number to round and yyy= the number of places
function roundyv3(nnn,yy y)
/* Preconditions :
abs(nnn) < 2^52 or thereabouts (you don't test for 'e' or 'E')
abs(yyy) < 20 or so (any more is pointless)
*/

-----ok---
{
//** the multiplier to use
var multy = "1e"+yyy;//*same as Math.pow(10, yyy) ***
nnn+=""; //** coerce nnn to a String
//make sure there's a dot and something after it
if (nnn.indexOf(". ") < 0){
nnn += ".0";
}
//** adding zeroes after the dot makes it behave when rounding
nnn = nnn + "00000";
//** now rounding works - but removes the dot if a whole number ***
I don't see why you converted nnn into a string when the next thing you
do is convert it back into the original number.
*************** *************

*** to make sure a decimal point and zeroes are there
*** else rounding is inconsistent************** ************
var strOut = String(Math.rou nd(nnn * multy) / multy);
//add back the decimal if rounding removed it and yyy > 0
if (strOut.indexOf (".") < 0 && yyy > 0) {
strOut+= ".0";
}
var placesInStrOut = strOut.length - strOut.indexOf( ".") - 1;
var zeroesNeeded = yyy - placesInStrOut;
var strZeroes = String(Math.pow (10, zeroesNeeded));
if (zeroesNeeded > 0) {
strOut += strZeroes.subst r(1);
}
return strOut;
}


John
--
John Harris

Apr 11 '06 #34
JRS: In article <h%************ *****@bignews6. bellsouth.net>, dated
Tue, 11 Apr 2006 00:14:15 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 numberof
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


** Here's latest version thanks to John's code-testing services
** removed some superfluous code and fixed the 1-digit bug

//**args ->nnn = the number to round and yyy= the number of places
function roundyv3(nnn,yy y){


BTW, it's a good convention IMHO to use, as in Fortran, names such as X
for floats and such as N for integers. Javascript does not make the
distinction, but it can help readability.
//** the multiplier to use
var multy = "1e"+yyy;//*same as Math.pow(10, yyy) ***
But "1e"+yyy gives a String; Math.pow(10, yyy) gives a Number.
nnn+=""; //** coerce nnn to a String
//make sure there's a dot and something after it
if (nnn.indexOf(". ") < 0){
nnn += ".0";
}
//** adding zeroes after the dot makes it behave when rounding
nnn = nnn + "00000";
When is that part beneficial, and how?
//** now rounding works - but removes the dot if a whole number ***
var strOut = String(Math.rou nd(nnn * multy) / multy);
//add back the decimal if rounding removed it and yyy > 0
if (strOut.indexOf (".") < 0 && yyy > 0) {
strOut+= ".0";
}
var placesInStrOut = strOut.length - strOut.indexOf( ".") - 1;
var zeroesNeeded = yyy - placesInStrOut;
var strZeroes = String(Math.pow (10, zeroesNeeded));
Why do that if zeroesNeeded is zero ? Also, it seems slower than using
a string constant of ten or twenty zeroes with substr.
if (zeroesNeeded > 0) {
strOut += strZeroes.subst r(1);
}
return strOut;
}


Your code gives funny results with large numbers and NaN .
Your code rounds 3.965 to 3.97 but -3.965 to -3.96 .

--
© 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 11 '06 #35
JRS: In article <Z4************ **@jgharris.dem on.co.uk>, dated Tue, 11
Apr 2006 21:16:17 remote, seen in news:comp.lang. javascript, John G
Harris <jo**@nospam.de mon.co.uk> posted :
In article <h%************ *****@bignews6. bellsouth.net>, Hal Rosser
<hm******@bell south.net> writes

<snip>
** Here's latest version thanks to John's code-testing services
** removed some superfluous code and fixed the 1-digit bug

//**args ->nnn = the number to round and yyy= the number of places
function roundyv3(nnn,yy y)


/* Preconditions :
abs(nnn) < 2^52 or thereabouts (you don't test for 'e' or 'E')
abs(yyy) < 20 or so (any more is pointless)
*/


You mean, I think, 2^53, the first integer that cannot be incremented
with ++. But the default conversion from Number to String does not use
e-format below almost 10^21.

Neither FAQ 4.6 nor my current code test for e/E as such; though they
detect them.

***

To use Bankers' Rounding sensibly, either it should be rounding to
integer (so x.5 is exact) or one should first round by a modest multiple
of the expected rounding error to an exact base-10 value (implying to a
string) and then do Bankers' on that.

--
© 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 12 '06 #36
In article <sW************ **@merlyn.demon .co.uk>, Dr John Stockton
<jr*@merlyn.dem on.co.uk> writes
JRS: In article <Z4************ **@jgharris.dem on.co.uk>, dated Tue, 11
Apr 2006 21:16:17 remote, seen in news:comp.lang. javascript, John G
Harris <jo**@nospam.de mon.co.uk> posted :
In article <h%************ *****@bignews6. bellsouth.net>, Hal Rosser
<hm******@bel lsouth.net> writes

<snip>
** Here's latest version thanks to John's code-testing services
** removed some superfluous code and fixed the 1-digit bug

//**args ->nnn = the number to round and yyy= the number of places
function roundyv3(nnn,yy y)


/* Preconditions :
abs(nnn) < 2^52 or thereabouts (you don't test for 'e' or 'E')
abs(yyy) < 20 or so (any more is pointless)
*/


You mean, I think, 2^53, the first integer that cannot be incremented
with ++. But the default conversion from Number to String does not use
e-format below almost 10^21.

<snip>

Displaying something.75 when there are only 2 bits to the right of the
binary point would be thoroughly misleading. Displaying something.00
when there are no bits to the right of the binary point is also
misleading.

Deciding what should be written in the pre-conditions is not easy in
this case. My "thereabout s" had a much larger range than you might have
thought.

John
--
John Harris
Apr 14 '06 #37

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
9530
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
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...
0
10236
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9055
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
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
5577
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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
3
2928
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.