Convert double to string in C

retched

Joined Dec 5, 2009
5,208
You should be able to get the variable length without having to convert to a string.

I think.

Are you just trying to find the amount of characters in the var?

If you want the size in bytes, you can use sizeof(); then divide to get the # of characters.
 
Last edited:

someonesdad

Joined Jul 7, 2009
1,583
There's no unique string representation of a given double, as there are lots of approximate choices. Examples: printf("%.3f", v), printf("%.8f, v), printf("%.4e", v).

If this isn't what you're after, then you'll have to give us a bit more of what you're after.
 

Thread Starter

hondabones

Joined Sep 29, 2009
123
Are you just trying to find the amount of characters in the var?
Yes. I need to know the number of characters in the variable.

2.34 has 4
100.34 has 6

etc.
someonesdad said:
There's no unique string representation of a given double, as there are lots of approximate choices. Examples: printf("%.3f", v), printf("%.8f, v), printf("%.4e", v).

If this isn't what you're after, then you'll have to give us a bit more of what you're after.
That isn't what I'm after.

Here's a snippet:
Rich (BB code):
while (Rs != l + 1)
{
	current = v/(Rs + l);
	p1 = (pow(current, 2)) * Rs;
	p2 = (pow(current, 2)) * l;
	p_resist = p1 * pow(10, 3);
	p_load = p2 * pow(10, 3);
			
//	int pr;
//	char buffer[10];
//	char len;
//	pr = sprintf(buffer, "%lf", p_resist);
//	printf("\n>>>%d\n", pr);

//	if (strlen(pr)  < 5)
//		strcat(pr, " ");

//		strcat(linetoprint, pr);
//		printf("%s", linetoprint);
What I'm trying to achieve is the values of the variables are output to the screen in a table/chart.(the code for this section is not in the snippet)

2.34 takes up less space than a variable with a value of 1234.56 thus, changing the width of the chart and deforming it when it outputs. I am attempting to check the size of the variable and adjust the chart/table with the appropriate adjustments.

Does this make sense?
 

rjenkins

Joined Nov 6, 2005
1,013
The conventional way would be to use fixed format in the printf statement,

Decide on the precision you want to use, like %6.2f or %4.5f

eg. rather than
printf("%lf", p_resist);
use
printf("%4.2lf", p_resist);

assuming you wanted four digits before the decimal point and two after. Adjust as required.

Your results will then print in neat columns.

When using floats, you will often get values that print to silly numbers of digits after the decimal point unless you fix the format, so trying to measure the length won't give meaningful results.

Edit: A bit of reference info:
http://en.wikipedia.org/wiki/Printf#printf_format_placeholders
 
Last edited:

Thread Starter

hondabones

Joined Sep 29, 2009
123
rjenkins,

That is precisely what I want (I think) I will have to sit down and play around with the printf statement to see what I can come up with.

As for the OP, I managed to get a working solution. Thanks to everyone for your help.

Jim
 
Top