Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create one only decimal number in C?

I’ve a problem: I would need to concatenate 3 double numbers into one only double number. For example, I’ve:

a = 40.000000;
b = 56.000000;
c = 10.236330;

I need the following number: 40.5610236330. The integer part is defined by the first two cyphers of a, the first two decimal cyphers are the integer part of b and the other decimal cyphers are all the cyphers of c. I’ve tried with:

k = a+(b/100)+(c/1000);

But due to approximation error, the result is 40.570236. Could you help me? Thank you so much!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Floating point calculation always loose some precision.

But 40.570236 instead of 40.5610236330 is too much off.

The big error you see is because of a simple bug in your code.

You need k = a+(b/100)+(c/10000); (i.e. c is to be divided by 10000)

Maybe it would be more clear if you did k = a+(b/100)+(c/100/100);

But never expect floating point calculation to 100% precise. It’s not even certain that the number 40.5610236330 can be represented in float/double

And further, the input values them self may be imprecise:

double c = 10.236330;
printf("%.20f\n", c);

Output:

10.23633000000000059515
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading