1. ...015ProjectsMyNumberFormatsMyNumberFormatsProgram.cs 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyNumberFormats
{
class Program
{
static void Main(string[] args)
{
// Declare Variables
double mynumber = new double();
Random myRnd = new Random();
// Initialise Variables
mynumber = 10000 * myRnd.NextDouble(); // 0 to 10000
// Print Results
Console.WriteLine($"The value is {mynumber}");
// Number Formats
Console.WriteLine($"The value is {mynumber.ToString("n")} (Number
Format)");
// Currency Format
Console.WriteLine($"The value is {mynumber.ToString("c")}
(Currency Format)");
// Scientific Formats
Console.WriteLine($"The value is {mynumber.ToString("e")}
(Scientific Format)");
Console.WriteLine($"The value is {mynumber.ToString("e2")}
(Scientific Format, 3 significant figures)" );
Console.WriteLine($"The value is {mynumber.ToString("e3")}
(Scientific Format, 4 significant figures)" );
// Fixed Formats
Console.WriteLine($"The value is {mynumber.ToString("f")} (Fixed
Format)");
Console.WriteLine($"The value is {mynumber.ToString("f3")} (Fixed
Format, 3 decimal places)"); // 3 decimal places
Console.WriteLine($"The value is {mynumber.ToString("f4")} (Fixed
Format, 4 decimal places)"); // 4 decimal places
// Percent Formats
Console.WriteLine($"The value is {mynumber.ToString("p")}
(Percent Format)");
Console.WriteLine($"The value is {mynumber.ToString("p1")}
(Percent Format, 1 decimal place)");
Console.WriteLine();
2. ...015ProjectsMyNumberFormatsMyNumberFormatsProgram.cs 2
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Using String.Format
Console.WriteLine($"Using String Formats");
Console.WriteLine(String.Format($"The value is {mynumber:n}
(Number Format)"));
Console.WriteLine(String.Format($"The value is {mynumber:c}
(Currency Format)"));
Console.WriteLine(String.Format($"The value is {mynumber:e}
(Scientific Format)"));
Console.WriteLine(String.Format($"The value is {mynumber:e2}
(Scientific Format, 3 significant figures)" ));
Console.WriteLine(String.Format($"The value is {mynumber:e3}
(Scientific Format, 4 significant figures)" ));
Console.WriteLine(String.Format($"The value is {mynumber:f}
(Fixed Format)"));
Console.WriteLine(String.Format($"The value is {mynumber:f3}
(Fixed Format, 3 decimal places)")); // 3 decimal places
Console.WriteLine(String.Format($"The value is {mynumber:f4}
(Fixed Format, 4 decimal places)")); // 4 decimal places
Console.WriteLine(String.Format($"The value is {mynumber:p}
(Percent Format)"));
Console.WriteLine(String.Format($"The value is {mynumber:p1}
(Percent Format, 1 decimal place)"));
}
}
}