Today we are sharing a small tip for VB.NET. If you want to round off a number to certain numbers after decimal, you can follow this tutorial. You can use Math class in order to round off a number to certain digits. Math class in VB.NET provides various options like Sine, Cos, Tan, Round, Square-root etc. But today we will be using Round
option only. Rounding off a number is very easy and you can do it using the code below:
Label1.Text = Math.Round(2.673491, 1)
Label1 is taken just for this example. You can choose either textbox or label to show the result. 2.673491 is the number which needs to be rounded off. You can write your own number instead of this example or just refer to some label’s text or textbox’s text like this:
Label5.Text = Math.Round(Textbox1.Text, 1)
If you’re inputting a number like we used (2.673491), take care of one thing. Don’t use inverted commas. If you do so, VB will underline the code and represent this as error. This is because we need to place a decimal no. and instead we are placing a string. Although, there’s decimal no. in the inverted commas but VB can’t know this. So don’t use inverted commas.
The 1 placed after comma represent the digits upto which you want to round off the number. You can customize it according to your preference but remember not to use inverted commas.
Here are few examples to consider:
Code: Label1.Text = Math.Round(2.673491, 1)
Code: Label1.Text = Math.Round(2.673491, 3)
Code: Label5.Text = Math.Round(Textbox1.Text, 1)
Result: Depends on Textbox1.Text property.
If you have any question or doubt, feel free to contact in comments 🙂
Join Us On Facebook and Twitter and you can subscribe via email too