Article 5QK4R CodeSOD: Price Conversions

CodeSOD: Price Conversions

by
Remy Porter
from The Daily WTF on (#5QK4R)

Russell F has an object that needs to display prices. Notably, this view object only ever displays a price, it never does arithmetic on it. Specifically, it displays the prices for tires, which adds a notable challenge to the application: not every car uses the same tires on the front and rear axles. This is known as a "staggered fitment", and in those cases the price for the front tires and the rear tires will be different.

The C# method which handles some of this display takes the price of the front tires and displays it quite simply:

sTotalPriceT1 = decTotalPriceF.ToString("N2");

Take the decTotalPriceF and convert it to a string using the N2 format- which is a number with thousands separators and two digits behind the decimal place. So this demonstrates that the developer responsible for this code understands how to format numbers into strings.

Which is why it's odd when, a few lines later, they do this, for the rear tires:

sTotalPriceT2 = decimal.Parse(decTotalPriceR.ToString("F2")).ToString("N2");

We take the price, convert it to a string without thousands separators, then parse it back into a decimal and then convert it to a string with thousands separators.

Why? Alone, this line would just be mildly irksome, but when it's only a few lines below a line which doesn't have this kind of ridiculousness in it, the line just becomes puzzling.

But the puzzle doesn't end. sTotalPriceT1 and sTotalPriceT2 are both string variables that store the price we're going to display. Because this price information may need to be retained across requests, though, someone decided that the prices also need to get stored in a session variable. In another method in the same class:

Session["FOS_TPriceF"] = bStaggered ? decimal.Parse(sTotalPriceT1).ToString("N2") : null;Session["FOS_TPriceR"] = bStaggered ? decimal.Parse(sTotalPriceT2).ToString("N2") : null;

Once again, we're taking a string in a known format, turning it back into the base numeric type, then formatting back to the format it already was. And I suppose it's possible that some other bit of code may have modified the instance variables sTotalPriceTN and broken the formatting, but it seems to me the solution is to not store numbers as strings and just format them at the moment of display.

buildmaster-icon.png [Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how! TheDailyWtf?d=yIl2AUoC8zAB9TM2X_wGSA
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments