Click here to Skip to main content
15,879,535 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi guys,
I just got stuck with conversion of a big floating value to string format.

In my program,


C++
void double_to_string(long double v)
{
  unsigned char res[40];
  
// here i am using compiler library function sprintf() which will give us the string format
  
  sprintf(res,"%f",v);
  if(strlen(res)>14)
  sprintf(res,"%Le",v);// if the result is having more number of digits
  return(res);

}

void fun1()
{
  long double v;
  unsigned char *result_str;
  v = 0.56726*6.456*1e-12; // based on some calculations i used to get this value
  result_str = double_to_string(v);
  print_result(result_str);
}


When i debug my code, in variable values i found the value of v in double_to_string function like this 3.66223056e-12. But in my sprintf() function giving 0.000000 as result. It's unable to convert such type of value to string. How can i over come this to get the correct results.

Note: My main intention is doing such big calculations and converting them in strings format with more accuracy. (Like our PC calculator)
Due to limitations of my display area, i am choosing exponent results if the resultant string is having more digits.

I hope i mentioned my problem clearly.So, If can any one have solution for this please help me out.Excuse for my poor english.
Posted
Updated 27-Sep-12 20:14pm
v5

Your arguments to sprintf() are backwards, the output string goes first, then the format statement, then the values to be formatted into the string. See here[^]

Also, the default precision (6) is not usually adequate for very small numbers. anything e-12 is pretty small. Try something like %.20f :)
 
Share this answer
 
v2
Comments
ccodeworld.blogspot.com 28-Sep-12 2:16am    
Thank u Chuck O'Toole..

Yeah, you are write.. By mistake here i have passed the arguments wrongly.i will rectify it in a moment.

If i use %.20f it's truncating the value after some digits. and more over, i don't have the display area to display 20 digits at a time.

If i have result string with more than 14 digits, i need to display in exponent format.
Is there anyway to achieve this.If it is there, please guide to do..

Thank you.
Chuck O'Toole 28-Sep-12 10:35am    
If you pass the arguments correctly, your statement with %Le should do the trick. Or use the link that I posted in the solution to look at all the ways available for formatting.
Look at the format type specifiers[^] for the one that suits your needs. In your case I would suggest the g code as the best choice.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900