Reading and Writing Floating-point Numbers

In this tutorial, we will learn how to read and write single and double precision floating-point numbers.


Reading and Writing Single Precision Floating-point Numbers

We have learned in our tutorial on Capabilities of Format Specifiers, that a single precision floating-point number can be read or written using %e, %f, or %g format specifiers. Recall that the %e format specifier is used to read or write a single precision floating-point number in scientific notation, %f in decimal notation, and %g in either scientific or decimal notation depending upon the size of the number. It’s important to note that reading or writing a double precision floating-point number requires a slightly different format specifier.


Reading and Writing Double Precision Floating-point Numbers

To read a double precision value, we need to add the letter “l” (small l) in front of e, f, or g. Here’s an example:

double x;
scanf(“%lf”, &x);

It is worth noting that adding l in front of e, f, or g has no effect in the printf function. You can use any of the format specifiers without the letter “l” to print float or double values.

To read or write a value of type long double, we need to add the letter “L” (capital L) in front of e, f, or g. Here’s an example:

long double x;
scanf(“%Lf”, &x);
printf(“%Lf”, &x);

Inside the printf function, it’s mandatory to use %Lf as the format specifier to print a long double value.


Summary

This tutorial explains how to read and write floating-point numbers in both single and double precision. It provides information on the format specifiers to use for each type of floating-point number and highlights the differences when working with double precision or long double values.



Leave a comment

Leave a comment

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

Thank you for choosing to leave a comment. Please be aware that all comments are moderated in accordance with our policy. For more information, please review our comments policy. Rest assured that your email address will not be shared with anyone. Kindly refrain from using keywords in your comment. Let’s maintain a respectful atmosphere and engage in meaningful conversations.