473,656 Members | 2,983 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Rounding floats/doubles

Hello,

This will probably be a simple question. How can I round float/doubles
to a specific digit after the comma/dot?

For example we have float i = 1.234567. I want to round it to 1.234.
Whan function should I use?

Jan 16 '06 #1
9 2684

printf("%.3f ",i);

rounds the number to 1.235

How to round it to 1.234.

Jan 16 '06 #2
itportal wrote:
printf("%.3f ",i);

rounds the number to 1.235

How to round it to 1.234.


One way is to sprintf() with "%f" specifier to a string buffer, and then
truncate resultant string to taste...

Cheers

Vladimir
--
My e-mail address is real, and I read it.
Jan 16 '06 #3
<it******@gmail .com> wrote:
For example we have float i = 1.234567. I want
to round it to 1.234.
and
printf("%.3f ",i);
rounds the number to 1.235


"1.235" is what most of us would call
the correct "rounded" value of "1.234567"

To "round it down", you could use truncf():

#include <math.h>
...
#define TWO_DIGITS 100.0
#define TREE_DIGITS 1000.0
#define FOUR_DIGITS 10000.0
...
float i, i_truncated;
i = 1.234567;
i_truncated = truncf(i * THREE_DIGITS) / THREE_DIGITS;
...

Use trunc(), if you are dealing with double variables.

I followed your example using 'i', even though it strongly
suggests an integer data type. (Or it is only for people
like me, who used FORTRAN long before using C ?)

Roberto Waltman

[ Please reply to the group, ]
[ return address is invalid. ]
Jan 16 '06 #4
itportal wrote:
Hello,

This will probably be a simple question. How can I round float/doubles
to a specific digit after the comma/dot?

For example we have float i = 1.234567. I want to round it to 1.234.
Whan function should I use?


I can't think of one -- after all, it's a fairly
unusual "rounding" rule that produces the more distant
of the two candidate values. However, you could use

#include <math.h>
...
float j = (float)(floor(i * 1000.0) / 1000.0);

I don't guarantee this will do what you want with negative
numbers (you didn't mention what you want). Also, the
similar version for `double' will probably misbehave with
starting values larger than DBL_MAX/1000. Finally, note
that eight significant digits are more than you have any
right to expect from a `float' ...

--
Eric Sosman
es*****@acm-dot-org.invalid
Jan 16 '06 #5
itportal wrote:
Hello,

This will probably be a simple question. How can I round float/doubles
to a specific digit after the comma/dot?

For example we have float i = 1.234567. I want to round it to 1.234.
Whan function should I use?


Oh, BTW, when I learned maths the rule was:

a.bcdef

if d<5 round to a.bc
else if d>5 round to a.b(c+1) and recurse for b
else if d==5 then
if c is even round to a.bc
else ronud to a.b(c+1) and recurse for b

Cheers

Vladimir
--
My e-mail address is real, and I read it.
Jan 16 '06 #6
>For example we have float i = 1.234567.

You *DO NOT* have a float of that value on a machine with binary
floating point.

If it's not an exact integer and the decimal representation doesn't
end in 5, there's no exact representation in binary floating point.
I want to round it to 1.234.
You *DO NOT* have a float of that value on a machine with binary
floating point.
Whan function should I use?


Multiply by 1000, floor() it, then divide by 1000. Dividing by 1000
re-introduces rounding error.
Gordon L. Burditt
Jan 16 '06 #7
"itportal" <it******@gmail .com> writes:
This will probably be a simple question. How can I round float/doubles
to a specific digit after the comma/dot?

For example we have float i = 1.234567. I want to round it to 1.234.
Whan function should I use?


Do want the rounded value to be a floating-point number, or do you
just want a string to be displayed somewhere?

If you want a numeric result, keep in mind that neither 1.234567 nor
1.234 can be represented exactly in binary floating-point. You can
get a close approximation to 1.234, but it could be either slightly
larger or slightly smaller than 1.234; if it's smaller, trying to
truncate it again could give you 1.233.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 16 '06 #8
The function below uses an integer cast to remove the fractional part
of the value after being pre-scaled. This is an alternative to using
the floor() function previously mentioned.

double truncate_digits (double d, int significant_dig its)
{
unsigned long int prescaler;

/* Construct the prescaler value for this number of digits */
for (prescaler = 1; significant_dig its > 0; significant_dig its--)
{
prescaler *= 10;
}

return ((long int)(d * prescaler) / (double)prescal er);
}

Will this perform the same on all C compilers?

Lucien Kennedy-Lamb

Jan 17 '06 #9
>The function below uses an integer cast to remove the fractional part
of the value after being pre-scaled. This is an alternative to using
the floor() function previously mentioned.

double truncate_digits (double d, int significant_dig its)
{
unsigned long int prescaler;

/* Construct the prescaler value for this number of digits */
for (prescaler = 1; significant_dig its > 0; significant_dig its--)
{
prescaler *= 10;
}

return ((long int)(d * prescaler) / (double)prescal er);
}

Will this perform the same on all C compilers?


No. Division by a power of 10 will introduce rounding error on
machines using binary floating point (that is: most of them) and
how much rounding error (and which direction) depends on the precision
of the floating point. This assumes that prescaler > 0 and
the exact result with infinite-precision math isn't an integer, which
covers just about all of the interesting uses of the function.

Oh, yes, even worse things happen if the calculation of prescaler
or d*prescaler overflows.

Gordon L. Burditt
Jan 17 '06 #10

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

Similar topics

13
25926
by: Shea Martin | last post by:
Any one have a better/simpler method for rounding a float to the nearest 1/10th? This is currently what I am using, and there must be a better way, or perhaps a canned method that I am not aware of. double z = atof(arg); z = z*100.0; int zi = (int)floor((double)z); int ri = zi%10; zi -= ri; zi += ( ri < 5 ) ? 0 : 10;
7
4095
by: Steven T. Hatton | last post by:
I'm surprised I haven't hit this situation till now, but I don't believe I've had to deal with it before. I have a function that sets the components of a point class (QPoint from Qt). It takes integer arguments for the components. I am calculating the values using transcendental functions sin and cos which return floating point type values. (The compiler claims they are double though I expected float in, float out.) I guess I have some...
2
1512
by: JNY | last post by:
Hello, I've searched for a solution, but can't find one. When adding two numbers I'm not getting the expected result: int testInt = 3056; float testMant = 0.9001; float testTotal; testTotal = testInt+testMant;
14
1676
by: my.correo.basura | last post by:
Yesterday I found in a piece of code a float being incremented with ++. For some reason (wrong, I guess...) I thought that only integer types could be incremented that way, and I had never seen floats or doubles incremented that way before. Just to be sure I did a toy program and compiled with gcc -ansi -pedantic -Wall and it worked without any error or warning, showing the correct result. Is it correct to increment floats or doubles with...
29
3163
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
13
6179
by: Shirsoft | last post by:
I have a 32 bit intel and 64 bit AMD machine. There is a rounding error in the 8th digit. Unfortunately because of the algorithm we use, the errors percolate into higher digits. C++ code is ------------------ b += (float)(mode *val); On 32 bit(intel , vs 2003, C++), some watch variables are
248
1510
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
6
2902
by: Pavel | last post by:
Hello, Does anyone know a (preferably open-source) multi-platform C or C++ library that would be able to write and read C/C++ doubles and floats to/from streambuf, char array or similar device in IEEE 754 with reasonably optimal precision and performance? The purpose is to exchange serialized doubles and floats between C/C++ and Java programs where Java serialization rules are used.
6
247
by: Razii | last post by:
What you need, instead of doubles and floats, is Multi-Precision Library. Too bad, as usual, it's not part of standard C++ library. Use GNU Bignum Library. All problems solved easily.
0
8816
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
8710
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
8598
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
7310
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...
1
6162
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
5627
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
4299
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2721
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
1598
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.