473,769 Members | 4,831 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Rounding a floating point number

Hi

"How can I round a number to x decimal places" ?

This question keeps appearing. I would propose the following
solution

#include <float.h>
#include <math.h>

double roundto(double x, int digits)
{
int sgn=1;

if (x == 0)
return 0;
if (digits DBL_DIG)
digits = DBL_DIG;
else if (digits < 1)
digits = 1;

if(x < 0.0) {
sgn = -sgn;
x = -x;
}
double p = floorl(log10l(x ));
p--;
p = digits-p;
double pow10 = pow(10.0, p);
return sgn*floor(x*pow 10+0.5)/pow10;
}

long double roundtol(long double x, int digits)
{
int sgn=1;

if (x == 0)
return 0;
if (digits LDBL_DIG)
digits = LDBL_DIG;
else if (digits < 1)
digits = 1;

if(x < 0.0) {
sgn = -sgn;
x = -x;
}
long double p = floorl(log10l(x ));
p--;
p = digits-p;
long double pow10 = powl(10.0, p);
return sgn*floorl(x*po w10+0.5)/pow10;
}
#include <stdio.h>
int main(void)
{
double d = 1.7888889988996 678;
long double ld = 1.7888889988996 678998877L;

for (int i = 0; i<=DBL_DIG;i++ ) {
printf("i=%d: %.15g\n",i,roun dto(d,i));
}
printf("\n 1.7888889988996 678\n");
for (int i = 0; i<=LDBL_DIG;i++ ) {
printf("i=%d: %.18Lg\n",i,rou ndtol(ld,i));
}
printf("\n 1.7888889988996 678998877L\n");
return 0;
}

--------------------------------------------------------------------
I would propose it to add it to the FAQ.
--
jacob navia
jacob at jacob point remcomp point fr
logiciels/informatique
http://www.cs.virginia.edu/~lcc-win32
Feb 25 '08 #1
20 5012
jacob navia said:
Hi

"How can I round a number to x decimal places" ?

This question keeps appearing.
<snip>
I would propose it to add it to the FAQ.
Good idea. You could call it Question 14.6.

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Feb 25 '08 #2

"Richard Heathfield" <rj*@see.sig.in validwrote in message
news:xc******** *************** *******@bt.com. ..
jacob navia said:
>Hi

"How can I round a number to x decimal places" ?

This question keeps appearing.

<snip>
>I would propose it to add it to the FAQ.

Good idea. You could call it Question 14.6.
14.6 is already used by How to Round a Number [to an integer]

--
Bart
Feb 25 '08 #3
Richard Heathfield wrote:
jacob navia said:
>Hi

"How can I round a number to x decimal places" ?

This question keeps appearing.

<snip>
>I would propose it to add it to the FAQ.

Good idea. You could call it Question 14.6.
Your kill file is not working apparently
:-)

That question addresses the rounding to nearest integer.
This answers the question of rounding to a number of decimal places

Not the same thing. But yes, we could add this to 14.6

--
jacob navia
jacob at jacob point remcomp point fr
logiciels/informatique
http://www.cs.virginia.edu/~lcc-win32
Feb 25 '08 #4
14.6 is already used by How to Round a Number [to an integer]
Then what need is there for this question? Its already answered in the faq.
Multiply, round then divide.
Feb 25 '08 #5
Bartc said:
>
"Richard Heathfield" <rj*@see.sig.in validwrote in message
news:xc******** *************** *******@bt.com. ..
>jacob navia said:
>>Hi

"How can I round a number to x decimal places" ?

This question keeps appearing.

<snip>
>>I would propose it to add it to the FAQ.

Good idea. You could call it Question 14.6.

14.6 is already used by How to Round a Number [to an integer]
From the FAQ, Q14.6: "You can round to a certain precision by scaling:

(int)(x / precision + 0.5) * precision"

(int)(3.141 / 0.01 + 0.5) * 0.01 gives us:

(int)(314.1 + 0.5) * 0.01 which is

(int)314.6 * 0.01 which is

314 * 0.01 which is

3.14

QED

(Of course, the usual caveats about floating point apply here.)

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Feb 25 '08 #6
On Mon, 25 Feb 2008 12:19:35 +0100,
jacob navia <ja***@nospam.c omwrote:
Richard Heathfield wrote:
>jacob navia said:
>>Hi

"How can I round a number to x decimal places" ?

This question keeps appearing.

<snip>
>>I would propose it to add it to the FAQ.

Good idea. You could call it Question 14.6.
That question addresses the rounding to nearest integer.
This answers the question of rounding to a number of decimal places
It also answers the question of how to round to a certain number of
digits:

\begin{quote}
You can round to a certain precision by scaling:
\end{quote}

Martien
--
|
Martien Verbruggen | prepBut nI vrbLike adjHungarian! qWhat's
| artThe adjBig nProblem? -- Alec Flett
|
Feb 25 '08 #7

"Richard Heathfield" <rj*@see.sig.in validwrote in message
news:oZ******** *************@b t.com...
Bartc said:
>>
"Richard Heathfield" <rj*@see.sig.in validwrote in message
news:xc******* *************** ********@bt.com ...
>>jacob navia said:

Hi

"How can I round a number to x decimal places" ?

This question keeps appearing.

<snip>

I would propose it to add it to the FAQ.

Good idea. You could call it Question 14.6.

14.6 is already used by How to Round a Number [to an integer]

From the FAQ, Q14.6: "You can round to a certain precision by scaling:

(int)(x / precision + 0.5) * precision"

(int)(3.141 / 0.01 + 0.5) * 0.01 gives us:

(int)(314.1 + 0.5) * 0.01 which is

(int)314.6 * 0.01 which is

314 * 0.01 which is

3.14
Yeah, you're right. Perhaps 14.6 should be written more clearly, with regard
to what exactly it means by Precision. And an example added, like yours.
>(int)(3.141 / 0.01 + 0.5) * 0.01
Somehow I would be happier if that was written as:
>(int)(3.141 *100 + 0.5) /100
Then any errors due to 0.01 not being exactly 1/100 are someone else's
fault.

--
Bart

Feb 25 '08 #8
MisterE wrote:
>14.6 is already used by How to Round a Number [to an integer]

Then what need is there for this question?
<Fx: swoosh sound of clue going over head>

--
Mark McIntyre

CLC FAQ <http://c-faq.com/>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt >
Feb 25 '08 #9
On Feb 25, 2:18*am, jacob navia <ja...@nospam.c omwrote:
Hi

"How can I round a number to x decimal places" ?

This question keeps appearing. I would propose the following
solution

#include <float.h>
#include <math.h>

double roundto(double x, int digits)
{
* * * * int sgn=1;

* * * * if (x == 0)
* * * * * * * * return 0;
* * * * if (digits DBL_DIG)
* * * * * * * * digits = DBL_DIG;
* * * * else if (digits < 1)
* * * * * * * * digits = 1;

* * * * if(x < 0.0) {
* * * * * * * * sgn = -sgn;
* * * * * * * * x = -x;
* * * * }
* * * * double p = floorl(log10l(x ));
* * * * p--;
* * * * p = digits-p;
* * * * double pow10 = pow(10.0, p);
* * * * return sgn*floor(x*pow 10+0.5)/pow10;

}

long double roundtol(long double x, int digits)
{
* * * * int sgn=1;

* * * * if (x == 0)
* * * * * * * * return 0;
* * * * if (digits LDBL_DIG)
* * * * * * * * digits = LDBL_DIG;
* * * * else if (digits < 1)
* * * * * * * * digits = 1;

* * * * if(x < 0.0) {
* * * * * * * * sgn = -sgn;
* * * * * * * * x = -x;
* * * * }
* * * * long double p = floorl(log10l(x ));
* * * * p--;
* * * * p = digits-p;
* * * * long double pow10 = powl(10.0, p);
* * * * return sgn*floorl(x*po w10+0.5)/pow10;}

#include <stdio.h>
int main(void)
{
* * * * double d = 1.7888889988996 678;
* * * * long double ld = 1.7888889988996 678998877L;

* * * * for (int i = 0; i<=DBL_DIG;i++ ) {
* * * * * * * * printf("i=%d: %.15g\n",i,roun dto(d,i));
* * * * }
* * * * printf("\n * * *1.788888998899 6678\n");
* * * * for (int i = 0; i<=LDBL_DIG;i++ ) {
* * * * * * * * printf("i=%d: %.18Lg\n",i,rou ndtol(ld,i));
* * * * }
* * * * printf("\n * * *1.788888998899 6678998877L\n") ;
* * * * return 0;

}

--------------------------------------------------------------------
I would propose it to add it to the FAQ.
This is the snippet's solution (which is very similar to yours):
/* round number n to d decimal points */
double fround(double n, unsigned d)
{
return floor(n * pow(10., d) + .5) / pow(10., d);
}

Of course, no solution is really going to be satisfying, as long as
the output format is floating point.
Another question is "What kind of rounding?" Do we want banker's
rounding or round to nearest or what?
Should we create a round function for each distinct floating point
type?
Feb 25 '08 #10

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

Similar topics

20
11729
by: Raoul Watson | last post by:
By any chance, anyone got a rounding routine that does a work around the VB "round" bug? I still find it amazing that a company as large as Microsoft would put out a math package that is so problematic.
6
9021
by: Curley Q. | last post by:
Is there a std lib rounding function that will round a real to a given number of decimal places? Something like: double round_it(double number, int decimal_digits) pass 34.5678, 3 to it and it returns 34.568
13
15626
by: kennethlou | last post by:
Hi, If in C a variable appears like X=10.000000, I can round it to zero decimal places. ie X=10? I then have to save the number into a variable. The method appears below: ************************************** >printf("Round % .f \n", 10.0000000);
29
3189
by: Marco | last post by:
Hello, I have : float f = 36.09999999; When I do : char cf; sprintf(cf,"%0.03lf", f); I get : 36.100
15
8063
by: Mukesh_Singh_Nick | last post by:
Why does floating point have a rounding error? How to work around it? For example, the following: flaot f = 1234.12345678F; printf("%2f\n", f) //prints 1234.123413 and
206
13303
by: md | last post by:
Hi Does any body know, how to round a double value with a specific number of digits after the decimal points? A function like this: RoundMyDouble (double &value, short numberOfPrecisions) It then updates the value with numberOfPrecisions after the decimal
0
9579
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
10032
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...
1
9979
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
9849
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...
0
8861
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
6661
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
5433
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3948
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
3551
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.