C Programming Tutorial 23 – Format Characters for Float and Double

Don’t forget to read the last blog on Scientific Notation with Floating Point Numbers! Are you new here? Start at the beginning, Intro to C!

Our program starts with a hardcoded floating point number in scientific notation and outputs that number in decimal notation. What I want to do is explore some of the other ways we can format this data and also how to take the input directly from the user rather than hard coding it.

First, let’s learn some format characters.

%f – display the number in decimal notation

%e – display the number in scientific notation

%g – let the computer decide how to format it

Formats it using scientific notation if the exponent is less than -4 or greater than 5. Otherwise, it uses decimal notation.

We will output our number once using each of the three format characters.

Now, we are going to learn how to take floating point numbers as input.

As I mentioned before, you have the option of using either the float or double data type, but I think you should be using double for nearly everything, so that is the data type we are going to be focusing on. Use whichever floats your boat (lol).

Format characters for taking input are similar, but you need to prefix it with an l.

You also need to prefix the variable name with the address-of operator.

You can actually use this format character to take data in either decimal notation or scientific notation, so you only have to remember one thing. You can use e or g instead of the f if you prefer as they can all be used to read data in either notation.

When we print, you can use %f, %e, and %g for both float and double, but with scanf, float and double are different. If you want to specifically read in a value as a double, you need to use the l prefix. Otherwise, you are reading in a value as a float. So scanf(%f, &var); is saying that you want to read in the value as a float, which we do not want to do.

I’m going to give you some more advanced information, so if you don’t understand it all yet, that is okay. We will get to it in more detail in upcoming videos.

The reason there is a difference between float and double for scanf() but not for printf() is that when we pass in a float to printf(), the function actually copies the value and stores it in a new variable of type double. This means that both float and double can be treated the same by printf().

With scanf(), we are using the address-of operator, which means we are actually passing in a pointer. Pointers stay the same in that if the original data type is float, the function will treat it as a float. This means we end up with two versions, %f for float, and %lf for double, depending on what you want to convert the input to. Let’s finish the program up!

Are you ready to learn more? Learn about ASCII in the next blog!

Leave a Reply

Your email address will not be published. Required fields are marked *