Quick Fix: Unwanted Rounding When String Formatting Number as Currency

By in ,
No comments

Sometimes it’s the little things you forget the easiest and most often that throw you for a loop. Today I was attempting to show a value in an ASP.NET MVC View which is stored as type long, representing a monetary amount in cents.

I formatted it as currency:

@string.Format("{0:c}", Model.Subtotal / 100)

But when I saw the output it rounded the value of 1250 to $12.00. This was strange since it was rounding down instead of up, which would still be incorrect, but at least make sense.

In an attempt to fix, I added a decimal place to the formatting:

@string.Format("{0:c2}", Model.Subtotal / 100)

But apparently currency is already set to two decimals. I can add more decimals, but it will always be zero, since it’s rounding.

I then realized that the Subtotal is long, which is an integer, as is of course 100, so it’s doing integer division. I need to cast one of the values to ensure the result doesn’t round. I defined the 100 value as a decimal by adding M at the end:

@string.Format("{0:c}", Model.Subtotal / 100M)

which revealed the expected output of $12.50 and I can go about my day.

It’s all so obvious in retrospect, but it’s one of those things that is easily forgotten. hopefully this note will help me remember!

as always, hope this was helpful and thanks for reading!

The following two tabs change content below.

selaromdotnet

Senior Developer at iD Tech
Josh loves all things Microsoft and Windows, and develops solutions for Web, Desktop and Mobile using the .NET Framework, Azure, UWP and everything else in the Microsoft Stack. His other passion is music, and in his spare time Josh spins and produces electronic music under the name DJ SelArom. His other passion is music, and in his spare time Josh spins and produces electronic music under the name DJ SelArom.