VB.net:显示十进制值的某些部分

VB.net:显示十进制值的某些部分,vb.net,Vb.net,在vb.net中,我想提取整数、小数、前两位小数以及第三位和第四位小数。我一直在绕着解决方案转,但不太清楚 到目前为止,我掌握的代码如下: Dim wholenumber As Decimal wholenumber = 15.1234 ' Displays 15 MsgBox("The whole number is " & Math.Floor(wholenumber)) ' Displays .1234 MsgBox("The decim

在vb.net中,我想提取整数、小数、前两位小数以及第三位和第四位小数。我一直在绕着解决方案转,但不太清楚

到目前为止,我掌握的代码如下:

 Dim wholenumber As Decimal
    wholenumber = 15.1234

    ' Displays 15
    MsgBox("The whole number is " & Math.Floor(wholenumber))
    ' Displays .1234
    MsgBox("The decimals are " & wholenumber - Math.Floor(wholenumber))
    ' Displays .12
    MsgBox("The first 2 decimals are" & ?????)
    ' Displays .0034
    MsgBox("The third and fourth decimals are " & ????)

在对数值调用
.ToString()
时,您希望使用格式说明符(该数值当前在代码中被隐式调用,但可能应该是显式的)

例如,
wholenumber.ToString(“##.#####”)应返回
“15.123”


您可以通过谷歌搜索“.net字符串格式”之类的内容找到更多信息,也可以找到大量信息和示例。

如果您想发挥创意,并使用基本的简单操作来完成所有工作,那么调用CInt(wholenumber)与Math.floor()是一样的。通过将小数点截断并乘以10的幂进行移位,您可以得到所需的一切

wholenumber = 15.1234
数字的整数部分
=CInt(wholenumber)
=15

小数是
=wholenumber-CInt(wholenumber)
=15.1234-15==0.1234

前两位小数是
=Cint((wholenumber-Cint(wholenumber))*100)/100
=Cint(0.1234*100)/100==12/100==0.12

3-4位小数是
=wholenumber-CInt(wholenumber*100)/100
=15.1234-CInt(1512.34)/100==15.1234-15.12==0.0034


等等。

这是我不知道的,但是你应该能够使用字符串操作函数来获取小数。像这样的

Dim wholeNumber As Decimal
Dim decimalPosition As Integer

wholenumber = 15.1234
decimalPosition = wholeNumber.ToString().IndexOf("."c)

MsgBox("The first 2 decimals are" & wholeNumber.ToString().Substring(decimalPosition + 1, 2))
MsgBox("The third and fourth decimals are " & wholeNumber.ToString().Substring(decimalPosition + 3, 2))

我最初使用wholenumber.ToString,但发现它正在返回.119999999和.0034000000000000096。就我而言,这不是一个太大的问题,但我认为他们可能是一个更好的方式。谢谢你的提示@user538149:在这种情况下,所有内容都与格式字符串有关。现在,如果您希望对实际值进行四舍五入,那么其他提供的答案将更有帮助。但是,如果您只是在谈论将值显示到指定的小数位数,那么字符串格式就是一种方法。+1并启用Option Strict,这样VB就不会自动转换,这很危险。
Dim wholeNumber As Decimal
Dim decimalPosition As Integer

wholenumber = 15.1234
decimalPosition = wholeNumber.ToString().IndexOf("."c)

MsgBox("The first 2 decimals are" & wholeNumber.ToString().Substring(decimalPosition + 1, 2))
MsgBox("The third and fourth decimals are " & wholeNumber.ToString().Substring(decimalPosition + 3, 2))