# Formatting Numbers using SI Prefixes

Well it’s time for another post. A couple of weeks ago I was working on an interface program for a rig at work. We were adding some extra features to a controller board and I thought while I was working on that I might as well make some changes to the interface program as well.  The feature I wanted to add to the program was to make it format some of the numbers that are displayed in the UI using SI prefixes and with units of measure.

So after a quick look on the web to see if I can find some example code on how to do this, I decided to have a go writing the code on my own without looking at other stuff too much. This is what I came up with, It’s a function written in C# that can be used to convert floating point numbers to formatted strings. So the number 0.102 will be printed as “102m”, and it can append units to the end like this – “102mA”.

public static string FormatStringEng(double input, string units, string format)
{
string prefix = "";
double value = 0.0;

if (input >= 1e+12 && input < 1e+15) {
prefix = "T"; value = (input / 1e+12);    // Tera (1e+12)
} else if (input >= 1e+9 && input < 1e+12) {
prefix = "G"; value = (input / 1e+9);     // Giga (1e+9
} else if (input >= 1e+6 && input < 1e+9) {
prefix = "M"; value = (input / 1e+6);     // Mega (1e+6)
} else if (input >= 1e+3 && input < 1e+6) {
prefix = "k"; value = (input / 1e+3);     // Kilo (1e+3)
} else if ((input >= 1) && (input < 1e+6)) {
prefix = ""; value = input;               // Unity
} else if (input >= 1e-3 && input < 1) {
prefix = "m"; value = (input * 1e+3);     // Milli (1e-3)
} else if (input >= 1e-6 && input < 1e-3) {
prefix = "μ"; value = (input * 1e+6);     // Micro (1e-6)
} else if (input >= 1e-9 && input < 1e-6) {
prefix = "n"; value = (input * 1e+9);     // Nano (1e-9)
} else if (input >= 1e-12 && input < 1e-9) {
prefix = "p"; value = (input * 1e+12);    // Pico (1e-12)
} else if (input >= 1e-15 && input < 1e-12) {
prefix = "f"; value = (input * 1e+15);    // Fempto (1e-15)
}

return value.ToString() + prefix + units;
}

This code is working quite well so far. Haven’t had any problems with it… yet anyway. That’s it for now, see ya!