小数舍入

时间:2019-03-05 16:21:41

标签: vb.net decimal rounding

我有一个项目,需要按以下方式四舍五入小数:

  

如果该数字介于12.01至12.49之间,则应四舍五入为12.00

     

如果该数字在12.50和12.99之间,则应四舍五入为13.00

我已经尝试过Math.Abs​​和Math.Round函数,但无法达到上述要求的确切结果。

3 个答案:

答案 0 :(得分:1)

Jacob is correct Math.Round does the job perfectly. Open a new project (Winforms) and add a Text box, button and label. Put this code behind the button click event.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
   Label1.Text = Math.Round(CDec(TextBox1.Text))
End Sub

Enter 12.01 to 12.49 in the textbox and it gets rounded down to 12 anything from 12.51 to 13.49 gets rounded to 13

答案 1 :(得分:1)

The following code seems to work for me, it rounds to the nearest whole number. So for example for the number 12.5 it rounds up to 13. Also, you may change the 0 in the code to change however many decimal places you would like to round to.

Dim a As Double = `your number`
Dim rounded As Double = Math.Round(a, 0, MidpointRounding.AwayFromZero)

答案 2 :(得分:0)

如banf所指出的那样,将附加参数添加到Math.Round函数中

私有子Button1_Click(作为对象发送,作为EventArgs发送)处理Button1.Click     Label1.Text = Math.Round(CDec(TextBox1.Text),0,MidpointRounding.AwayFromZero) 结束