0

I'm using Decimals in VB.NET to hold values for currency. It is possible on my website to add a discount to an item, which is inputted into a text box and then the value is retrieved in the code-behind.

Dim discountValue As Decimal = 0
discountValue = Decimal.Round(Convert.ToDecimal(txtDiscount.Text), 2)
lblDiscount.Text = "£" & discountValue.ToString()

However, when I view the label after adding the discount, it is not rounded to 2 decimal points.

Is there any reason this is not working? What am I doing wrong in this approach?

Note: I'm using ASP.NET VB.NET and the page is wrapped inside an UpdatePanel.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
a--
  • 558
  • 2
  • 15
  • Why not [letting `String.Format` round it](https://stackoverflow.com/a/7076918/107625) for you? E.g. `String.Format("{0:0.00}", discountValue);` or `discountValue.ToString("0.00")`. – Uwe Keim Aug 22 '17 at 13:44
  • Have you tried putting a break point to see where the error is? I copy/pasted your code in a console application and it's working. What is the value of txtDiscount.Text ? – the_lotus Aug 22 '17 at 13:49
  • @UweKeim I didn't even think of that!! It works now, thank you :) – a-- Aug 22 '17 at 13:49
  • @MorganLane if String.Format worked but ToString didn't, then the rounding setting is in your culture information, you should check the value of CurrentCulture.NumberFormat.NumberDecimalDigits – the_lotus Aug 22 '17 at 13:59
  • @the_lotus Will take a look into that. – a-- Aug 22 '17 at 14:04

1 Answers1

3

It's because ToString() just formats it without the decimal points if the number is *.00
Change this line:

lblDiscount.Text = "£" & discountValue.ToString("N2")
MatSnow
  • 7,357
  • 3
  • 19
  • 31
  • 3
    Or `lblDiscount.Text = discountValue.ToString("C2")` to automatically use the currency symbol for the current culture. – Blackwood Aug 22 '17 at 13:57
  • @Blackwood Yeah, even better, depending on the needs of the OP. – MatSnow Aug 22 '17 at 14:04
  • I like this way more, saves me having to worry about the currency symbol in the future. – a-- Aug 22 '17 at 14:05
  • 1
    @MorganLane Now I think about it. `lblDiscount.Text = discountValue.ToString("C")` should automatically use the appropriate number of decimal places for the current culture (2 in the case of UK and US). – Blackwood Aug 22 '17 at 14:28