0

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.)

3
Contributors
6
Replies
8
Views
5 Years
Discussion Span
Last Post by dannyniu
0

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.

0

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.

0

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 by Dani: Formatting fixed

0

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.