Pogram to demonstrate number formatting
- Write a program to demonstrate number formatting in C
- Write a program to demonstrate number formatting in C++
- Write a program to demonstrate number formatting in Python
- Write a program to demonstrate number formatting in PHP
- Write a program to demonstrate number formatting in Java
- Write a program to demonstrate number formatting in Java Script
- Write a program to demonstrate number formatting in C#
Explanation:
Programming frequently involves formatting numbers to make sure they are shown in a way that is readable by humans or in a certain way (e.g., rounding, inserting commas, fixed decimal places). An explanation of how it’s done in different programming languages is provided below:
Formatting methods:
- Rounding Numbers:
- Limit the number of decimal places.
- Adding Commas or Grouping:
- Add commas as thousand separators.
- Aligning Output:
- Control the width and alignment of numbers.
- Percentage, Scientific Notation, and Currency Formats.
Pogram to demonstrate number formatting
-
C
-
C++
-
Python
-
PHP
-
JAVA
-
Java Script
-
C#
#include <stdio.h> int main() { double num = 12345.6789; printf("Number: %.2f\n", num); // 2 decimal places printf("Padded Number: %08.2f\n", num); // Zero-padded printf("Scientific Notation: %e\n", num); // Scientific notation return 0; }
#include <iostream> #include <iomanip> int main() { double num = 12345.6789; std::cout << "Number: " << std::fixed << std::setprecision(2) << num << std::endl; // 2 decimal places std::cout << "Padded Number: " << std::setw(10) << std::setfill('0') << num << std::endl; // Zero-padded std::cout << "Scientific Notation: " << std::scientific << num << std::endl; // Scientific notation return 0; }
num = 12345.6789 print(f"Number: {num:.2f}") # 2 decimal places print(f"Padded Number: {num:010.2f}") # Zero-padded print(f"Scientific Notation: {num:.2e}") # Scientific notation
<?php $num = 12345.6789; printf("Number: %.2f\n", $num); // 2 decimal places printf("Padded Number: %010.2f\n", $num); // Zero-padded printf("Scientific Notation: %e\n", $num); // Scientific notation ?>
public class Main { public static void main(String[] args) { double num = 12345.6789; System.out.printf("Number: %.2f%n", num); // 2 decimal places System.out.printf("Padded Number: %010.2f%n", num); // Zero-padded System.out.printf("Scientific Notation: %.2e%n", num); // Scientific notation } }
let num = 12345.6789; console.log(`Number: ${num.toFixed(2)}`); // 2 decimal places console.log(`Padded Number: ${num.toFixed(2).padStart(10, '0')}`); // Zero-padded console.log(`Scientific Notation: ${num.toExponential(2)}`); // Scientific notation
using System; class Program { static void Main() { double num = 12345.6789; Console.WriteLine($"Number: {num:F2}"); // 2 decimal places Console.WriteLine($"Padded Number: {num,10:F2}"); // Padded Console.WriteLine($"Scientific Notation: {num:E2}"); // Scientific notation } }