ryan thomas ryan thomas - 1 month ago 6
Vb.net Question

How can I round double values?

My question is the bigmac works fine when I press the bigmacadd button and minus button. But when I press the mcdouble add button, I get a bunch of numbers. How can I make it so it shows 2.50 as decimal places?

Public Class Form1
Const bigmac As Decimal = 4D
Const mcdouble As Decimal = 2.25
Dim tax As Decimal
Dim price As Decimal
Dim quantity As Integer
Dim finaltotal As Decimal

Private Sub Btnbigmacadd_Click(sender As Object, e As EventArgs) Handles Btnbigmacadd.Click
quantity = quantity + 1
txtquan.Text = quantity

price += bigmac
txtprice.Text = price

tax = price * 0.15
txttax.Text = tax

finaltotal = price + tax
txtfinaltotal.Text = finaltotal
End Sub

Private Sub btnbigmacminus_Click(sender As Object, e As EventArgs) Handles btnbigmacminus.Click
quantity = quantity - 1
txtquan.Text = quantity

price -= bigmac
txtprice.Text = price

tax = price * 0.15
txttax.Text = tax

finaltotal = price + tax
txtfinaltotal.Text = finaltotal
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
quantity = quantity + 1
txtquan.Text = quantity

price += mcdouble
txtprice.Text = price

tax = price * 0.15
txttax.Text = tax

finaltotal = price + tax
txtfinaltotal.Text = finaltotal
End Sub
End Class

Answer

You can round tax to two decimal places using the Math.Round method

tax = Math.Round(price * 0.15D, 2)
txttax.Text = tax.ToString()

finaltotal = price + tax
txtfinaltotal.Text = finaltotal.ToString()

If want to keep the extra decimal places in tax and finaltotal, but show only two decimal places in the text boxes, you can use the ToString("N2") method.

tax = price * 0.15D
txttax.Text = tax.ToString("N2")

finaltotal = price + tax
txtfinaltotal.Text = finaltotal.ToString("N2")