Thought for the Dazed

I've had to give up that Distance Learning course as I was having trouble seeing the teacher.

Flickr
www.flickr.com
RobMiles' items Go to RobMiles' photostream
Twitter
C# Yellow Book

Search entire site
« Windows Phone taskhost.exe error | Main | Delegates, Events and Confusion »
Friday
Jul302010

Quick Number Formatting in C#

IMG_2184

I’ve been playing with the Windows Phone accelerometer, and displaying results. Thing is, it gives me values which have lots of decimal places that I don’t really want. They make the numbers flicker in a way that hurts my head. What I want is a way to just display them to two decimal places.

I must admit that previously I’ve resorted to very dodgy behaviour at this point, such as multiplying by 100, converting to an integer and then dividing by 100 again. Must be my old assembler ways coming back to haunt me. Turns out that there is a much easier way of doing this in C# which is to use the string formatter:

message = "Accelerometer" +
    "\nX: " + string.Format( "{0:0.00}",accelState.X) +
    "\nY: " + string.Format( "{0:0.00}", accelState.Y) +
    "\nZ: " + string.Format( "{0:0.00}", accelState.Z) ;

This little block of magic gets the X, Y and Z values out of a vector and then displays them to two decimal places in a string I can display in my XNA program.

The key is the {0:0.00} bit in the format, which gives a pattern for the display of the first (and only) value to be converted. This pattern says a single leading digit and two decimal places.

If you want to do interesting things like put commas into numbers (so that you can print 1,234,567 type values) then you can do that too. You can find out more about how the format strings work in my C# Yellow book (subtle plug) starting on page 50.

Reader Comments (4)

You could just do:

message = string.Format("Accelerometer\nX: {0:00.00}\nY: {0:0.00}\nZ: {0:0.00}", accelState.X, accelState.Y, accelState.Z);
July 30, 2010 | Unregistered Commenter[ICR]
You shouldn't use '\n', it's not portable, you should instead use System.Environment.NewLine.
July 30, 2010 | Unregistered CommenterBen
Thanks for those (although for ICR's idea to work you'd probably have to number the second and third format placeholders {1:0.00} and {2:0.00}).

I guess this is why code reviews are such a good idea...
July 30, 2010 | Registered CommenterRob
Thanks for that tip Rob, as for sticking commas in number's I didn't know it was possible without some jiggery pokery.
July 31, 2010 | Unregistered CommenterJoel

PostPost a New Comment

Enter your information below to add a new comment.
Author Email (optional):
Author URL (optional):
Post:
 
All HTML will be escaped. Hyperlinks will be created for URLs automatically.