Hi can u pls tel me how to tackle a problem like this:
1234567890123456 is the number to be loaded in db... i need to convert it to double without using atof()... if i use atof() function the number is rounded off to 1234567890123460... ??? can anyone suggest for a solution without using atof function... currently the code is like this :
ram.item_number = (double)atof((char*)im.itemNum);

(Note: both ram.item_number and im.itemNum belong to double datatype.)

if i use atof() function the number is rounded off to 1234567890123460... ???

Can you post a complete test program that shows this round off error? For example, does the following work?

#include <stdio.h>
#include <stdlib.h>
#include <float.h>

int main(void)
{
    const char *s = "1234567890123456";
    
    printf("DBL_MAX: %f\n\n", DBL_MAX);
    printf("Conversion: %f\n", atof(s));
    
    return 0;
}

ram.item_number = (double)atof((char*)im.itemNum);
(Note: both ram.item_number and im.itemNum belong to double datatype.)

If im.itemNum is a double, then your code is flat out wrong and shouldn't compile. If im.itemNum is a string, then the cast is unnecessary. And the cast on atof() is most certainly unnecessary given that atoi() already returns double.

That number has 16 places, and according to IEEE.754, the maximum accuracy of double is about 15 places in total.
You can use uint64_t instead (or without stdint.h, unsigned long long),
in this integer case, the CPU can still make an accurate calculation with it then.

That number has 16 places, and according to IEEE.754, the maximum accuracy of double is about 15 places in total.
You can use uint64_t instead (or without stdint.h, unsigned long long),
in this integer case, the CPU can still make an accurate calculation with it then.

ram.item_number = atof((char*)lim.Num);

now also ended up with same prob... can u pls tel me a solution...

Edited 3 Years Ago by Dani: Formatting fixed

Write your customized number string analysing function.
Prepare a variable called SUM in any type you want(unsigned/signed int8~64, float32~64)
Read the chars one by one. Each time, multiply SUM by ten.
Once hits a ".", divide the value of that char by some negative power of ten,
then add to SUM.

This article has been dead for over six months. Start a new discussion instead.