Skip to content
Fix Code Error

Correct format specifier for double in printf

March 13, 2021 by Code Error
Posted By: Anonymous

What is the correct format specifier for double in printf? Is it %f or is it %lf? I believe it’s %f, but I am not sure.

Code sample

#include <stdio.h>

int main()
{
   double d = 1.4;
   printf("%lf", d); // Is this wrong?
}

Solution

"%f" is the (or at least one) correct format for a double. There is no format for a float, because if you attempt to pass a float to printf, it’ll be promoted to double before printf receives it1. "%lf" is also acceptable under the current standard — the l is specified as having no effect if followed by the f conversion specifier (among others).

Note that this is one place that printf format strings differ substantially from scanf (and fscanf, etc.) format strings. For output, you’re passing a value, which will be promoted from float to double when passed as a variadic parameter. For input you’re passing a pointer, which is not promoted, so you have to tell scanf whether you want to read a float or a double, so for scanf, %f means you want to read a float and %lf means you want to read a double (and, for what it’s worth, for a long double, you use %Lf for either printf or scanf).



1. C99, §6.5.2.2/6: “If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions.” In C++ the wording is somewhat different (e.g., it doesn’t use the word “prototype”) but the effect is the same: all the variadic parameters undergo default promotions before they’re received by the function.

Answered By: Anonymous

Related Articles

  • Most effective way to parse JSON Objects
  • problem with client server unix domain stream…
  • Does moment.js allow me to derive a timezone…
  • Callback functions in C++
  • How to properly do JSON API GET requests and assign…
  • C++ template,typename and operator
  • List of Timezone IDs for use with FindTimeZoneById() in C#?
  • GLYPHICONS - bootstrap icon font hex value
  • Draw in Canvas by finger, Android
  • C++ OpenGL stb_image.h errors
  • Getting infinite loop after entering 2 objects to…
  • Why is 2 * (i * i) faster than 2 * i * i in Java?
  • How can I create an executable to run a kernel in a…
  • How to store the recursive value in my map in…
  • Scanf/Printf double variable C
  • integrating disqus with emberjs only works on first…
  • Add element to an array embedded inside a…
  • Azure Availability Zone ARM Config
  • Adding gif image in an ImageView in android
  • I do not use TBB, but I get linker errors related to TBB
  • The 'compilation' argument must be an instance of…
  • How to parse JSON with XE2 dbxJSON
  • Fastest way to iterate over all the chars in a String
  • Why doesn't the height of a container element…
  • NullpointerException error while working with…
  • no match for ‘operator
  • Undefined reference to 'vtable for ✘✘✘'
  • Avoid creating new session on each axios request laravel
  • What are the undocumented features and limitations…
  • I have just started learning function pointers in C…
  • Event Snippet for Google only shows one event while…
  • Why is my loop stopping at the first argument (char…
  • Start redis-server with config file
  • Search match multiple values in single field in…
  • Creating an dynamic array, but getting segmentation…
  • Printf width specifier to maintain precision of…
  • C++ error: expected class member or base class name…
  • Android Image View Pinch Zooming
  • Auto-fit TextView for Android
  • OpenCL - Approximation of Pi via Monte Carlo…
  • Draw multiple lines using OpenGL 3.0+ in C
  • Can the type of a function be constrained to certain…
  • What is the issue with this QOpenGLWidget?
  • Why does this Azure Resource Manager Template fail…
  • How do i update a javascript variable as its value changes?
  • Octave using 'for' statement to show two animations…
  • Why are elementwise additions much faster in…
  • Knight's tour Problem - storing the valid moves then…
  • Implementation of user defined array on stack and/or…
  • loop and eliminate unwanted lines with beautiful soup
  • Searching for matching elements between 2 arrays in C
  • Ukkonen's suffix tree algorithm in plain English
  • mongodb group values by multiple fields
  • How to format a phone number in a textfield
  • Equals(=) vs. LIKE
  • What is the difference between "long", "long long",…
  • C Argument number to create PGM images
  • SDL_SetRenderTarget() hangs for a while if multiple…
  • Why does declared array size not affect the size of…
  • How to pass 2D array (matrix) in a function in C?
  • fork() and wait() with two child processes
  • Smart way to truncate long strings
  • Program.Mattor(): not all code paths return a value.…
  • Azure CLI - az deployment group create -…
  • Is there any possible way to loop strcmp function in…
  • Cannot open include file: 'stdio.h' - Visual Studio…
  • Copy a file in a sane, safe and efficient way
  • What should main() return in C and C++?
  • Generating a drop down list of timezones with PHP
  • TLS 1.3 server socket with Java 11 and self-signed…
  • Is the term "format specifier" a synonym for term…
  • C# Get YouTube videoId from Json
  • Blazor Can't Update UI
  • How do I limit the number of digits from 6 to 4 in…
  • Angular 12 - Generating browser application bundles…
  • Efficient Algorithm for Bit Reversal (from…
  • What do these operators mean (** , ^ , %, //)?
  • Where's the DateTime 'Z' format specifier?
  • C++ Switch statement to assign struct values
  • Correct format specifier to print pointer or address?
  • Simple C example of doing an HTTP POST and consuming…
  • Polymer + Dart2js Not Working
  • How do I pass an array of structures to a function?
  • String.Format for Hex
  • How to initalize a array of string from a file data
  • C compile error: Id returned 1 exit status
  • How to traverse the complex nested Json in C# and…
  • Siemens LOGO! PLC data in the wrong order
  • TCP client/server in c
  • delete item in array of struct that has char array…
  • Is it possible to print a variable's type in standard C++?
  • gcc/g++: "No such file or directory"
  • Head pointer not accessible when creating a method…
  • ./components/Avatar.tsx Error: Cannot find module…
  • Baffling variadic templates exercise
  • A homework is about use macro
  • Why does this core dumped error happen in my class?…
  • How to filter a RecyclerView with a SearchView
  • Jenkins with nginx using docker Port 50000 config
  • Accessing a Shared File (UNC) From a Remote,…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Identify if a string is a number

Next Post:

Check if an element is present in an array

Leave a Reply Cancel reply

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

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error