Coding Challenge – Reduce “If/Else” Chain

After reading a request posted on a programming Discord channel for a way to make a repeated if/else chain cleaner, here is my attempt.

Below is the original code posted by a user, who wanted to add significantly more weights to their code, but wanted a cleaner approach than just adding more else statements:

if (silicon > 1000000000000000)
{
suffix = "mt";
siliconVis = silicon * .000000000000001f;
}
else if (silicon > 1000000000000)
{
suffix = "kt";
siliconVis = silicon * .000000000001f;
}
else if (silicon > 1000000000)
{
suffix = "t";
siliconVis = silicon * .000000001f;
}
else if (silicon > 1000000)
{
suffix = "kg";
siliconVis = silicon * .000001f;
}
else if (silicon > 1000)
{
suffix = "g";
siliconVis = silicon * .001f;
}
else if (silicon > 0)
{
suffix = "mg";
siliconVis = silicon;
}

I used a new class and a dictionary to calculate the display, meaning new weight labels could be added to the code just by adding a single new dictionary entry.
The code can be seen and run at dotnetfiddle

Leave a Reply

Your email address will not be published. Required fields are marked *