j-nunn.com

This is the personal hompage of John  Nunn, a software developer based in Coventry, U.K..

I own a software development company (Tortrix Ltd.) providing software solutions and I.T. services to the Health Care industry. Our solutions include knowledge management dashboards, intranet & extranet solutions using Microsoft Office SharePoint Server as well as bespoke solutions.

When not trying to earn a living I help to run a number of Developer comunities, I manage the Midlands Developer network; and I am the regional co-ordinator for VBUG in the midlands.

Latest Blog Posts

Go Back

Formatting decimal data with C#

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

Facebook Twitter DZone It! Digg It! StumbleUpon Technorati Del.icio.us NewsVine Reddit Blinklist Add diigo bookmark

Post a comment!
  1. Formatting options
       
     
     
     
     
       
Copyright © 2010 John Nunn
This site is powered by