Monday 2 June 2014

String.Format and Cargo Cult Formatting

While working on a port of our Surface Level app to a universal app, I stumbled across some exceptions being thrown in a great matrix library I picked up from here:

http://blog.ivank.net/lightweight-matrix-class-in-c-strassen-algorithm-lu-decomposition.html

Internally, the code was eventually calling

String.Format("{0,5:0.00}", v);


and the bug was caused by a leading space while parsing.


I’ve noticed this string before in some of the Microsoft accelerometer samples, but never actually looked at what it did.


It turns out the ,5 makes the field right justified, filling 5 characters, and padding with spaces.  In all of my testing up to now, I never saw this, but somehow on the latest device, I saw a value of 0, which ended up with a leading space.


The bug has now been fixed by the author in another way, but it points out the importance of actually reading every line of code, and understanding it before you put something into a project.

No comments:

Post a Comment