← Back

22. Multiply Decimals with Precision

Easy

📝 Problem

Multiply two decimal numbers and print the product with a precision of 2 decimal places.

Input Format:
Accept two decimal values as input
Output Format:
Print the product with 2 precision
Constraints:
1 ≤ N1, N2 ≤ 10^15
Sample Input 1:
2.24 3.56
Sample Output 1:
7.97
Sample Input 2:
125.58 78.65
Sample Output 2:
9876.87
💡 Key Concepts

What You'll Learn:

  • Long Double Type: Handling high-precision decimal numbers (up to 10^15)
  • fixed Manipulator: Forcing fixed-point notation (not scientific)
  • setprecision(): Controlling decimal places in output
  • Combining Manipulators: Using multiple formatting options together

🔍 Understanding the Components

📌 Breaking Down the Solution:
// 1. Why long double?
long double f1, f2;  // Handles very large decimals

// 2. Read two decimal numbers
cin >> f1 >> f2;  // Space-separated input

// 3. Format and print the product
cout << fixed              // Fixed-point notation
     << setprecision(2)    // 2 decimal places
     << f1 * f2;          // Calculate and print

📊 Float Types Comparison

Type Size Precision Range
float 4 bytes ~7 digits ±3.4 × 10^38
double 8 bytes ~15 digits ±1.7 × 10^308
long double 12-16 bytes ~19 digits ±1.1 × 10^4932
💡 Why Use Long Double Here?
The constraint (up to 10^15) requires maximum precision. long double ensures we can handle very large decimal values and their multiplication without losing accuracy.

🎯 The Power of fixed + setprecision()

📌 Without vs With fixed:
double num = 1234567.89;

// Without fixed (might use scientific notation)
cout << setprecision(2) << num;
// Output: 1.2e+06 (scientific notation!)

// With fixed (always decimal format)
cout << fixed << setprecision(2) << num;
// Output: 1234567.89 (decimal format!)
⚠️ Important: Always use fixed before setprecision() when you want exact decimal places. Without fixed, large numbers might switch to scientific notation!

🧮 How It Works

📌 Step-by-Step Example:
// Input: 2.24 3.56
f1 = 2.24
f2 = 3.56

// Multiplication:
f1 * f2 = 7.9744  // Actual result

// With setprecision(2):
7.97  // Rounded to 2 decimal places

// Example 2: 125.58 * 78.65 = 9876.8670
// Output: 9876.87

🔗 The <iomanip> Library

The <iomanip> library provides I/O manipulators:

  • setprecision(n) - Set decimal precision
  • setw(n) - Set field width
  • setfill(c) - Set fill character
  • fixed - Use fixed-point notation
  • scientific - Use scientific notation
  • left/right - Set alignment

This is one of the most commonly used libraries for formatted output in C++!

💻 Solution Code
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    long double f1, f2;
    cin >> f1 >> f2;
    
    cout << fixed << setprecision(2) << f1 * f2;
    
    return 0;
}