One problem I recently faced was an application that printed directions for
drug prescriptions. The main problem I was facing was only showing decimal
places if the user entered them. For example the user may have wanted to
prescribe 1.25ml of a drug however if when the meant 1ml 1.00ml appeared on the
prescription the user felt this could be confused as 100ml. luckily there is an
easy solution to this. By using a numeric format string, you can change the way
in which numeric data is formatted as a string.
There are two types of Numeric Format Strings Standard and Custom.
Standard Numeric Format Strings
- Currency C or c
- Decimal D or d
- Exponential (or Scientific) E or e
- Fixed Point F or f
- General G or G
- Number N or n
- Percent P or p
- Round-trip R or r
- Hexadecimal X or x
Custom Numeric Format Strings
- Zero Placeholder 0
- Digit Placeholder #
- Decimal Point .
- Thousand separator and number scaling ,
- Percentage placeholder %
- Scientific notation E0 or E+0 or E-0 or e0 or e+0 or e-0
- Literal string ‘ABC’
- Section separator ;
In order to achieve the desired effect a custom numeric format string was
needed, the following c# code shows the use of a custom numeric format string to
achieve the desired result.
double x = 1.25;
double y = 1.50;
double z = 1.00;
Console.WriteLine(String.Format("x={0}, y={1}, z={2}", x.ToString("0.##"), y.ToString("0.##"), z.ToString("0.##")));
Generates
x=1.25, y=1.5, z=1