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.