简体   繁体   中英

How can I set an output value to 2 decimal places in Visual Studio?

Im putting together a basic Gross Profit Calculator in Visual Studio and need the output to show as a £ value, ie to 2 decimal places.

I have tried this so far:

String.Format("{0:0.00}", TextBox3.Text = CStr(sale))

where TextBox3 is the output for the calculation. However on using this, nothing happens and the box remains empty and I can't work out why!

Your syntax is not correct, re-write your code this way:

TextBox3.Text = String.Format("{0:0.00}", sale)

The String.Format 's result wasn't being assigned to anything.

The syntax is wrong, and besides, CStr is just another way to format other types as a string. By using it you prevent String.Format from doing its job

I think you are looking for

TextBox3.Text = String.Format("{0:0.00}", sale) 

Furthermore, built-in numeric types override ToString and allow custom formatting as well. If sale is a float, double or decimal, you can write:

TextBox3.Text = sale.ToString("0.00")

or

TextBox3.Text = sale.ToString("N2")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM