简体   繁体   中英

C and Floating Point

I've written a program in C and Im using cJSON to encapsulate data and send up to Firebase.

I simply want the number to be a number so I can do some calculations on it in Firebase.

This is where it gets messy.

double 24.9

This gives back

24.899999999999999

So eg,

round((399 / 16.0) * 10.0) / 10.0 = 24.8999999

I only want one decimal place, I want 24.9, I need it to be represented as a number. Looks like I might just have to do a sprintf() and use a RAW in cJSON. Unless there's another way in C to keep my 24.9 as 24.9.

This question is not enquring about how floating point works. I am aware of issues. I have not however seen a suitable method to solve it.

C floating point can't do that.

What you can do is represent the number in milli-whatever like this:

int 24900

You'd be surprised how often it is the most viable solution when systems wish to express and communicate floating point

dec24.9 is to binary what dec1/3 is to decimal : a number with an infinite number of decimals.

The only way (I'm aware of - there might be actual solutions) to pass through this difficulty is to put the number into a string, using sprintf indeed.

char *num = malloc(); //Large enough to contain the result or else... SEGFAULT
sprintf(&num, "%.2f", YOUR_MATH_HERE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM