Advertisement
nmnikolov

05. FormattingNumbers

Jun 16th, 2014
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.77 KB | None | 0 0
  1. using System;
  2.  
  3. //Write a program that reads 3 numbers: an integer a (0 ≤ a ≤ 500), a floating-point b and a floating-point c and prints them in 4 virtual columns on the console. Each column should have a width of 10 characters. The number a should be printed in hexadecimal, left aligned; then the number a should be printed in binary form, padded with zeroes, then the number b should be printed with 2 digits after the decimal point, right aligned; the number c should be printed with 3 digits after the decimal point, left aligned.
  4. //Examples:
  5. //
  6. //   a        b         c       result
  7. // 254     11.6       0.5      |FE        |0011111110|     11.60|0.500     |
  8. // 499  -0.5559     10000      |1F3       |0111110011|     -0.56|10000     |
  9. //   0        3   -0.1234      |0         |0000000000|         3|-0.123    |
  10.  
  11. class FormattingNumbers
  12. {
  13.     static void Main()
  14.     {
  15.         Console.Write("Input integer a (0 <= a <= 500): ");
  16.         short a = short.Parse(Console.ReadLine());
  17.         Console.Write("Input floating-point b: ");
  18.         float b = float.Parse(Console.ReadLine());
  19.         Console.Write("Input floating-point c: ");
  20.         float c = float.Parse(Console.ReadLine());
  21.         Console.WriteLine();
  22.  
  23.         //Print a in hexadecimal, left aligned
  24.         Console.Write("|{0,-10:X}", a);
  25.  
  26.         //Print a in binary, padded with zeroes
  27.         string aBinary = Convert.ToString(a, 2).PadLeft(10, '0');
  28.         Console.Write("|{0}", aBinary);
  29.  
  30.         //Print b with 2 digits after the decimal point, right aligned
  31.         Console.Write(b % 1 == 0 ? "|{0,10}" : "|{0,10:F2}", b);
  32.  
  33.         //Print c with 3 digits after the decimal point, left aligned
  34.         Console.WriteLine(c % 1 == 0 ? "|{0,-10}|" : "|{0,-10:F3}|", c);
  35.  
  36.         Console.WriteLine();
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement