473,385 Members | 1,326 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Problem with printf formats

I have following code:

int main(void)
{
printf("%.3lf\n",-2158470*0.001);
}

it prints

-2158.470

How can i disable '0' at the end, if they are not needed ?

Is there a possibility just to write %lf and just print as many digits
as needed to represent the number ?


Dec 20 '05 #1
16 1863

Guenther Sohle said:
(...) printf("%.3lf\n",-2158470*0.001); (...) it prints

-2158.470

How can i disable '0' at the end, if they are not needed ? Is there a
possibility just to write %lf and just print as many digits as needed to
represent the number ?


The problem is not in the printf() function, but in the way floating point
numbers are represented by your computer. Due to rounding errors, floating
point numbers hardly ever have the 'exact' value you would expect. Search
google for 'floating point' for some details, or read this wikipedia page:
http://en.wikipedia.org/wiki/Floating_point.

It is up to you to make the choice how many digits are significant in a
number, so that is why you should tell printf() about this.
--
:wq
^X^Cy^K^X^C^C^C^C
Dec 20 '05 #2
Guenther Sohler wrote:

I have following code:

int main(void)
{
printf("%.3lf\n",-2158470*0.001);
}

it prints

-2158.470

How can i disable '0' at the end, if they are not needed ?

Is there a possibility just to write %lf and just print as many
digits as needed to represent the number ?


You are asking the wrong question. The trailing zero is needed to
represent the number. Otherwise how could you distinguish it from:

printf("%.2f\n", -2158471 * 0.001)

(always assuming that -2158471 does not create an overflow)

Your question, I believe, is "how to suppress trailing zeroes". A
little thought and an intermediary buffer should give you a
suitable answer for that.

--
A: Because it fouls the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Dec 20 '05 #3
Guenther Sohler:
int main(void)
{
printf("%.3lf\n",-2158470*0.001);
}

it prints

-2158.470

How can i disable '0' at the end, if they are not needed ?

Is there a possibility just to write %lf and just print as many digits
as needed to represent the number ?


The l in %lf is superfluous, just use %f.
To avoid the trailing zeros try %g.

Jirka
Dec 20 '05 #4
On Tue, 20 Dec 2005 13:56:44 +0100, Jirka Klaue wrote:
Guenther Sohler:
int main(void)
{
printf("%.3lf\n",-2158470*0.001);
}

it prints

-2158.470

How can i disable '0' at the end, if they are not needed ?

Is there a possibility just to write %lf and just print as many digits
as needed to represent the number ?
The l in %lf is superfluous, just use %f.

Thank you for the info. To avoid the trailing zeros try %g.
I also tried %g:
int main(void)
{
printf("%g\n",-2158475*0.001);
}

which results in
-2158.47

one digit is missed! this is a killing issue for me!

how can i have the proper value displayed in all cases ?
Jirka


Dec 20 '05 #5
On Tue, 20 Dec 2005 12:08:23 +0000, usenet wrote:

Guenther Sohle said:

(...)
printf("%.3lf\n",-2158470*0.001);

(...)
it prints

-2158.470

How can i disable '0' at the end, if they are not needed ? Is there a
possibility just to write %lf and just print as many digits as needed to
represent the number ?


The problem is not in the printf() function, but in the way floating point
numbers are represented by your computer. Due to rounding errors, floating
point numbers hardly ever have the 'exact' value you would expect. Search
google for 'floating point' for some details, or read this wikipedia page:
http://en.wikipedia.org/wiki/Floating_point.

It is up to you to make the choice how many digits are significant in a
number, so that is why you should tell printf() about this.


I know, but the accuracy of double should still good enough to fulfill my
purpose!
Dec 20 '05 #6
On Tue, 20 Dec 2005 07:06:42 -0500, Chuck F. wrote:
Guenther Sohler wrote:
>
I have following code:

int main(void)
{
printf("%.3lf\n",-2158470*0.001);
}

it prints


Your question, I believe, is "how to suppress trailing zeroes". A
little thought and an intermediary buffer should give you a
suitable answer for that.


Thank you for the information. Yes, I also keep this in mind,
but i use %f very often in my code ( > 100) and to suitable
handle all them, I would have to write my own printf.
I dont like to do this unless I am really sure there is no other way
Dec 20 '05 #7
Guenther Sohler:
I also tried %g:
int main(void)
{
printf("%g\n",-2158475*0.001);
}

which results in
-2158.47

one digit is missed! this is a killing issue for me!
Well, then it's time for you to read the appropriate part
of the standard.

ISO/IEC 9899:TC2
7.19.6.1#8
g,G A double argument representing a floating-point number is converted
in style f or e (or in style F or E in the case of a G conversion
specifier), depending on the value converted and the precision.
Let P equal the precision if nonzero, 6 if the precision is omitted,
or 1 if the precision is zero. Then, if a conversion with style E
would have an exponent of X:
- if P > X ≥ -4, the conversion is with style f (or F) and
precision P - (X + 1).
- otherwise, the conversion is with style e (or E) and precision P - 1.
Finally, unless the # flag is used, any trailing zeros are removed from
the fractional portion of the result and the decimal-point character is
removed if there is no fractional portion remaining.

So try %.9g or something like that.
how can i have the proper value displayed in all cases ?


This could be difficult depending on the meaning of proper.

Jirka
Dec 20 '05 #8
In article <pa****************************@newlogic.com> Guenther Sohler <gu*************@newlogic.com> writes:
....
int main(void)
{
printf("%g\n",-2158475*0.001);
}

which results in
-2158.47

one digit is missed! this is a killing issue for me!

how can i have the proper value displayed in all cases ?


But, what *is* the proper value? In binary it is:
-10000110110.01110011001100110011...
and that is what is stored on the computer, most decimal numbers are
not exactly representable in binary. So what will be stored is a
rounded value, and the value in memory is:
-2158.47499999999990905052982270717620849609375
so what should the system do?

--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Dec 20 '05 #9
Jirka Klaue wrote:
Guenther Sohler:
Is there a possibility just to write %lf and just print as many digits
as needed to represent the number ?


The l in %lf is superfluous, just use %f.


It is superfluous in C99, and is an error in C89. But most
C89 compilers allow it anyway.

Dec 20 '05 #10
Guenther Sohler wrote:
I have following code:

int main(void)
{
printf("%.3lf\n",-2158470*0.001);
}

it prints

-2158.470

How can i disable '0' at the end, if they are not needed ?

Is there a possibility just to write %lf and just print as many
digits as needed to represent the number ?

Question "How can I disable '0' at the end" indicates somekind of
misconception of floating point numbers.

Count of digits in a number indicates the accuracy of the number. So,
if you just remove zero from a number, you decrease accuracy of the
number.

For example:
-2158.5 could be result of rounding -2158.470, but it would be wrong
to add zeros to -2158.5 because the accurate amount was -2158.470.

The significance of zeros in indicating accuracy can be only perceived
when handling numbers on right side of decimal point.
For example:
-2000 could be result of rounding -2158 or it could be the exact
amount. You cannot tell if -2000 has one, two, three or four
significant digits, i.e. if -2000 is accurate to first, second, third
or fourth digit.
This is why scientific notation is used to represent quantities.
E.g. -2.000e3 is different from -2e3 in accuracy.
--
It's bit too late to be clear, but I hope I made my point through.

C faq: http://www.eskimo.com/~scs/C-faq/top.html
Reference: http://www.acm.uiuc.edu/webmonkeys/book/c_guide/
Coding standards: http://www.psgd.org/paul/docs/cstyle/cstyle.htm
Dec 21 '05 #11
Guenther Sohler wrote:
...
I know, but the accuracy of double should still good enough to fulfill my
purpose!
...


What exactly do you mean by "good enough" and "your purpose" in this case? Most
of the time floating-point numbers that have innocent-looking decimal
representations have infinitely long [periodic] representations in traditional
binary positional notation. For example, both '0.001' and '2158.47' are such
numbers. It is impossible to represent them precisely in 'double', which
probably means that 'double's precision (or precision of any type of same
structure, no matter how large) is definitely not "good enough" (assuming that I
understood your "good enough" correctly).

--
Best regards,
Andrey Tarasevich
Dec 21 '05 #12
>> I know, but the accuracy of double should still good enough to fulfill my
purpose!
...


What exactly do you mean by "good enough" and "your purpose" in this case?

(I'm not the original poster).

It is difficult and very expensive to measure most any physical
quantity to more significant digits than are present in a double.
(15 in a typical IEEE float implementation). Exceptions may include
currency and time.

Gordon L. Burditt
Dec 21 '05 #13
Guenther Sohler wrote:
I have following code:

int main(void)
{
printf("%.3lf\n",-2158470*0.001);
}

it prints

-2158.470

How can i disable '0' at the end, if they are not needed ?

Is there a possibility just to write %lf and just print as many digits
as needed to represent the number ?


I can write a function to do it.

#include <stdio.h>
#include <string.h>

char *sprintd(char *buf, size_t buf_size, double val, int precision)
{
/* write value into string */
snprintf(buf, buf_size, "%.*f", precision, val);

/* find decimal point */
char *p = strchr(buf, '.'), *q;

/* remove trailing zeros */
if(p) for(q = strchr(p, 0) - 1; *q == '0'; --q) *q = 0;

/* remove trailing decimal point */
if(p && p[1] == 0) p[0] = 0;

return buf;
}

int main(void)
{
char buf[100];
printf("%s\n", sprintd(buf, sizeof buf, 355.0 / 113.0, 15));
return 0;
}

--
Simon.
Dec 21 '05 #14
write %.2lf inn place of %.3lf

Dec 21 '05 #15
"vishnu" <er*******@gmail.com> writes:
write %.2lf inn place of %.3lf


What?

Read <http://cfaj.freeshell.org/google/>.

--
Keith Thompson (The_Other_Keith) 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.
Dec 21 '05 #16
Guenther Sohler wrote:
On Tue, 20 Dec 2005 12:08:23 +0000, usenet wrote:

Guenther Sohle said:

(...)
printf("%.3lf\n",-2158470*0.001);


(...)
it prints

-2158.470

How can i disable '0' at the end, if they are not needed ? Is there a
possibility just to write %lf and just print as many digits as needed to
represent the number ?


The problem is not in the printf() function, but in the way floating point
numbers are represented by your computer. Due to rounding errors, floating
point numbers hardly ever have the 'exact' value you would expect. Search
google for 'floating point' for some details, or read this wikipedia page:
http://en.wikipedia.org/wiki/Floating_point.

It is up to you to make the choice how many digits are significant in a
number, so that is why you should tell printf() about this.

I know, but the accuracy of double should still good enough to fulfill my
purpose!

You are perhaps confusing accuracy and precision. A double will always
be precise to 53 bits or 16 digits or whatever. Its value is often less
accurate than that, depending on how it was contrived.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Dec 21 '05 #17

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

Similar topics

1
by: Bangalore | last post by:
Hi all, I was trying out the following program, I want to copy the content of struct x variable to file. Here using write of fwrite(used with FILE *fl) I am not able to write integer part to...
9
by: Bill Cunningham | last post by:
I know this must have some simple answer but I'm having trouble with this function I wrote. stdio.h math.h double relstr (double x,double y) {double n; n=x/y; printf("%f",(return n;));} I...
11
by: aldrin | last post by:
I'm trying to run this code under windows xp sp2 using codeblocks v1.0 compiler with great difficulty.There is no problem with running this under KDevelop in linux. Any help would be greatly...
26
by: Schizoid Man | last post by:
Hi, I have a very strange arithmetic problem in C: double t = 0.1; int steps = 10; double time_step = t / (double)steps; I would expect the output of time_step to be 0.01000 (my output is...
4
by: Andre | last post by:
Hi, Could someone tell me what's wrong with the following program? I think there is something wrong with the size of integers I'm using, but not sure. When I execute it, I get the following...
5
by: Sanjay Kulkarni | last post by:
I am facing some problems while trying to explore the printf statement: Expected Actual Result Statement Result 1 printf("x = %d", 18.0 / 14); 18725 5.0 printf("\nx = %f",...
18
by: Scott | last post by:
Hi, a problem with this following code is really bugging me. tform = fopen(country, "r"); fseek(tform, 9L, SEEK_SET); fgets(player2, 38, tform); printf("Player Name (save): %s", player);...
25
by: jacob navia | last post by:
The C99 standard forgot to define the printf equivalent for complex numbers Since I am revising the lcc-win implementation of complex numbers I decided to fill this hole with "Z" for...
15
by: Ioannis Vranos | last post by:
I recall from previous discussions here, that we must cast a non-void pointer to void * before printing its value with printf("%p"). Is it true, and if yes why?
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.