Solved

EASY - how do you printout .1 instead of 0.1

Posted on 2004-08-26
12
253 Views
Last Modified: 2010-04-15
Simple, stupid question
long bleh = .1
printf("%f\n", bleh)
prints out 0.1
i need:
printf("%<something_here>f\n", bleh)
so that the end output is just .1 instead of 0.1. If I can't get this to work I will have to figure out if my value is between 0 and 1 and then parse it using some sort of 'Right' function... much more work than i think i need.
Thanks


0
Comment
Question by:jramrus
  • 4
  • 4
  • 2
  • +1
12 Comments
 
LVL 22

Accepted Solution

by:
grg99 earned 25 total points
Comment Utility

I don't see a format spec for this, but you could:

char Buf[50];

snprintf( Buf, sizeof( Buf ), "%f", bleh );

printf( "%s", &Buf[ Buf[0] == '0' && Buf[1] == '.'  ] );

0
 

Author Comment

by:jramrus
Comment Utility
to make sure the solution doesn't work for just this case, here are several examples
.000001
1.00000
99999.9

so the precision depends on the value

Possibly there is a better way to do take a double and convert it to a character array than sprintf where the 0. in 0.1 isn't automatically put in?
0
 

Author Comment

by:jramrus
Comment Utility
my current, really ugly solution

char* seven_total_characters(double myval)
// returns 7 characters for any input > 0 and < 99999.9
{
      char* temp, *temp2;
      temp = (char*)malloc(7);
      temp2 = (char*)malloc(strlen(temp)*sizeof(char));
      if(myval < 1)
      {
            sprintf(temp, "%0.6f", myval);
            sprintf(temp2, "%s", temp+1);
            strcpy(temp, temp2);
      }
      else
      {
            if(myval < 10)
                  sprintf(temp, "%0.5f", myval);
            else if(myval < 100)
                  sprintf(temp, "%0.4f", myval);
            else if(myval < 1000)
                  sprintf(temp, "%0.3f", myval);
            else if(myval < 10000)
                  sprintf(temp, "%0.2f", myval);
            else if(myval < 100000)
                  sprintf(temp, "%0.1f", myval);
      }      
      free(temp2);
      return temp;
}

any improvements that anyone can see? if i need 8 characters, the entire thing changes. i'm sure there is a better way to do it.
0
 
LVL 22

Expert Comment

by:grg99
Comment Utility
So what's wrong with my solution above?  :)

0
 
LVL 45

Assisted Solution

by:sunnycoder
sunnycoder earned 25 total points
Comment Utility
I assume that you have two arguments. Buffer is large enough to sprintf the biggest double

char * remove_leading_zeros ( double myval, char * buffer )
{
         char * temp;
         sprintf ( buffer, "%lf", myval );
         temp = buffer;
         while ( *temp == '0' && *temp != '.' && *temp != '\0' )
                  temp++;
         return temp;
}

you can easily add range checks for making sure that value is between 0 and 99999.9 or any other number you desire. This will give you any amount of precision you desire. If you want only 7 digits, you can strncpy from temp to temp+7 and return that value, you do not have to add a check for all possible value ranges.

cheers
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Expert Comment

by:dtvjho
Comment Utility
Your first line:
long bleh = .1
is suspicious. What compiler are you using? My Solaris Forte cc is ANSI and it truncates .1 thereby assigning zero to my long.

Regarding
printf("%<something_here>f\n", bleh)
you could use %.1f and this will yield "0.1". To drop the leading zero you could use sprintf followed by printf:

sprintf(buffer, "%.1f", bleh);
printf("%s\n", &buffer[1]);

Yes, this is a narrow solution as it would not handle input values with more than one digit on either side of the decimal. Let us know if you expect values that don't fit this pattern.
0
 

Author Comment

by:jramrus
Comment Utility
grg99.... i must admit, i could not get snprintf to work at all. I will look into this further when i get a chance.

sunnycoder, unless i'm using it wrong, an input of '99999.0' yields '9999.000000'. THE most important characteristic of the result is that it is 7 total characters long.

dtvjho, my appologies, as you can see from the code I was using I changed it from a long to a double. Using %.1f, as you already know, would not work for many cases, as can be shown by my code that had to do this
          if(myval < 10)
               sprintf(temp, "%0.5f", myval);
          else if(myval < 100)
               sprintf(temp, "%0.4f", myval);
          else if(myval < 1000)
               sprintf(temp, "%0.3f", myval);
          else if(myval < 10000)
               sprintf(temp, "%0.2f", myval);
          else if(myval < 100000)
               sprintf(temp, "%0.1f", myval);

It appears that I am not going to get the trivial solution I wanted. Possibly a better approach is to just throw my double into a string(just using %f), and then take the string and manually pad it with 0's until I get the final result to be the right length. I think I can do that in very few lines, and it would work for all cases. Thoughts?
0
 

Author Comment

by:jramrus
Comment Utility
actually sunnycoder, your solution might work better than i first thought
0
 
LVL 22

Expert Comment

by:grg99
Comment Utility
sunny's while condition:

 *temp == '0' && *temp != '.' && *temp != '\0'


looks mighty peculiar.   if the first part is true (*temp == '0'), then the second and third parts HAVE to be true.  

If the first part is false,then the other two parts, due to the "&&", are never evaluated.

I humbly submit that my clever entry does very much the same thing, but without the complexity and excess baggage of the above.

0
 
LVL 45

Expert Comment

by:sunnycoder
Comment Utility
Clever code grg99 ... :) ... needs someone like you to come up with that

However, is it guaranteed that true would always evaluate to 1 ... Isn't 2 or 3 or anything non zero, a perfectly valid true value ?

jramrus ,

>sunnycoder, unless i'm using it wrong, an input of '99999.0' yields '9999.000000'. THE most
>important characteristic of the result is that it is 7 total characters long.

char * remove_leading_zeros ( double myval, char * buffer )
{
         char * temp;
         sprintf ( buffer, "%lf", myval );
         temp = buffer;
         while ( *temp == '0' && *temp != '.' && *temp != '\0' )
                  temp++;
         temp+7='\0';  /*adding a string terminator character after 7 characters.*/
         return temp;
}

make sure that you pass valid buffer to the function and free it in the calling program (if you malloced it, that is) after you have finished using it.
0
 
LVL 22

Expert Comment

by:grg99
Comment Utility

>However, is it guaranteed that true would always evaluate to 1 ...

The result of a comparison operator always results in 0 or 1.


> Isn't 2 or 3 or anything non zero, a perfectly valid true value ?

True also.  A somewhat debatable decision that Dennis Richie musta made at 3 AM someday which has reverberated down thru the ages.  Estimated cost so far:  $600,000,000.  But it saves a little typing.


0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now