C Decimal (Floating-Point) Numbers
In this page:
What are Decimal (Floating-Point) Numbers?
Decimal numbers, also called floating-point numbers, represent values with a fractional part and require a type like float or double, since int and other integer types can only store whole numbers.
Example: What are Decimal (Floating-Point) Numbers?
#include <stdio.h>
int main() {
float price = 9.99f;
printf("%.2f", price);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
float Precision
float is a single-precision floating-point type that typically stores about 6 to 7 significant decimal digits accurately, using 4 bytes of memory, making it more compact but less precise than double.
Example: float Precision
#include <stdio.h>
int main() {
float f = 1.0f / 3.0f;
printf("%.7f", f);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
double Precision
double is a double-precision floating-point type that typically stores about 15 to 16 significant decimal digits, using 8 bytes of memory, and is the default choice for decimal literals and most floating-point math in C.
Example: double Precision
#include <stdio.h>
int main() {
double d = 1.0 / 3.0;
printf("%.15f", d);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Formatting Decimal Output
printf's %f specifier can be customized with a precision, like %.2f for exactly two decimal places, and a field width to control how the formatted decimal number is aligned and padded in the output.
Example: Formatting Decimal Output
#include <stdio.h>
int main() {
double value = 3.14159;
printf("%.2f", value);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Comparing Floating-Point Numbers
Because floating-point numbers are stored in binary and can't represent every decimal value exactly, comparing two floating-point values for exact equality is unreliable, and checking whether their difference is smaller than a small tolerance is the standard approach instead.
Example: Comparing Floating-Point Numbers
#include <stdio.h>
#include <math.h>
int main() {
double a = 0.1 + 0.2;
double b = 0.3;
if (fabs(a - b) < 1e-9) {
printf("Equal enough");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- C Introduction
- C History & Features
- C Environment Setup
- C First Program
- C Syntax & Structure
- C Statements
- C Comments
- C Keywords & Identifiers
- C Data Types
- C Character Data Type
- C Numeric Data Types
- C Decimal (Floating-Point) Numbers
- C sizeof Operator
- C Extended Data Types
- C Type Conversion
- C Booleans
- C Variables
- C Changing Variable Values
- C Multiple Variables
- C Constants
- C Fixed-Width Integers