Module: VARIABLES. OUTPUT FORMATS


Problem

5/5

Output Accuracy

Theory Click to read/hide

Output Specifiers
To output real values, just call the Console.Write or Console.WriteLine:
method   double a = 0.9999; Console.Write(a);  
But sometimes you need to pre-format the output of values, it is convenient to do this using the String.Format method, more details here.
Output with a certain precision
For formatting fractional numbers, the f specifier is used, the number after which indicates how many characters will be after the separator. double a = 12.123; Console.WriteLine(String.Format("{0:f2}", a)); The result will be 12,12, but if you use the value 0.9999, uncontrolled rounding will occur and   1.00.

Therefore, the following algorithm is used to discard signs rather than rounding:
1) multiply the original value by 10, as many times as you need to leave decimal places;
2) using the   Math.Truncate method, we leave only the integer part;
3) divide the resulting value by 10, as many times as you need to leave decimal places.

Example for output with two decimal precision: 
double a = 0.9999; a = a * Math.Pow(10, 2); a = Math.Truncate(a); a = a / Math.Pow(10, 2);
 
The type of separator when outputting the result (dot or comma) depends on the regional settings of the computer, so to always use a period as a separator, you need to change the regional settings to invariant, resulting example:
 
CultureInfo ci = new CultureInfo(""); double a = 0.9999; a = a * Math.Pow(10, 2); a = Math.Truncate(a); a = a / Math.Pow(10, 2); Console.WriteLine(a.ToString(ci));

Problem

Write a program that prints the value of a variable to 2 decimal places.