0

I have DiscountTotal variable with decimal type. Values are set on code behind the page, after page is loaded the values are rounded.

<%#DataBinder.Eval(Container.DataItem, "DiscountTotal","{0:C}")%>

Value 7610.3250D is being displayed as £7610.33. I like this to be displayed as £7610.32 or $7610.32 depending on logged in user. Current Culture settings are already there and i am only worry about rounding.

user1263981
  • 2,953
  • 8
  • 57
  • 98
  • What's the difference in question? – VDWWD Feb 01 '19 at 20:27
  • other one is to find out the reason why values are being rounded and this one is to find out how values can be rounded in right format. – user1263981 Feb 01 '19 at 20:28
  • Ok. Close vote retracted... – VDWWD Feb 01 '19 at 20:31
  • Possible duplicate of [C# Double - ToString() formatting with two decimal places but no rounding](https://stackoverflow.com/questions/2453951/c-sharp-double-tostring-formatting-with-two-decimal-places-but-no-rounding) – Amr Elgarhy Feb 01 '19 at 22:27

2 Answers2

0

Try rounding with a MidpointRounding

decimal value = 7610.3250m;
string formattedValue = string.Format("{0:C}", decimal.Round(value, 2, MidpointRounding.ToEven));
VDWWD
  • 35,079
  • 22
  • 62
  • 79
0

Assuming that the underline datatype of your DiscountTotal property is System.Decimal, you could use this in order to provide the appropriated culture to the ToString method, so it can render the currency symbol based on the specified culture.

// For $, use en-US instead of en-GB.
// You must make this available in your session.
var sessionUiCulture = new System.Globalization.CultureInfo("en-GB");
...
...
<%# decimal.Round((decimal)DataBinder.Eval(Container.DataItem, "DiscountTotal"), 2, MidpointRounding.ToEven).ToString("C", sessionUiCulture) %>

Also, if you need this behavior across your application, the best way to accomplish this is by setting the property System.Globalization.CultureInfo.CurrentUICulture to the appropriated culture in your request pipeline, this way you don't have to worry about this.

Depending on what route you go, you should consider creating an extension method for this:

public static string ToCurrency(this decimal value)
{
    return decimal.Round(value, 2, MidpointRounding.ToEven).ToString("C");
}

So you could just do:

<%# ((decimal)DataBinder.Eval(Container.DataItem, "DiscountTotal")).ToCurrency() %>
yv989c
  • 1,453
  • 1
  • 14
  • 20