开发者

VB.net: Displaying certain portions of a decimal value

In vb.net I want to pull out the wholenumber, decimal, first 2 decimal places and 3rd and 4th decimals. I've been circling around the solution but not quite there.

The code I have so far is here:

 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
  开发者_JAVA百科  MsgBox("The third and fourth decimals are " & ????)


You want to use a format specifier when calling .ToString() on your numeric values (which is currently being called implicitly in your code, but should probably be explicit).

For example, wholenumber.ToString("##.###") should return "15.123".

More information can be found here, and tons of information and examples can be found by Googling something like ".net string formatting".


' Displays .12
Console.Writeline("The first 2 decimals are " & _
    decimal.Round(wholenumber, 2) - decimal.Round(wholenumber,  0))
' Displays .0034
Console.Writeline("The third and fourth decimals are " & _
    (wholenumber - decimal.Round(wholenumber, 2)))


If you want to be creative and do it all using basic simple operations, calling CInt(wholenumber) is the same as Math.floor(). You can get everything you need with a combination of truncating and shifting the decimal by multiplying powers of 10.

wholenumber = 15.1234

The integer part of the number = CInt(wholenumber) =15

The decimals are = wholenumber - CInt(wholenumber) = 15.1234 - 15 == 0.1234

The first 2 decimals are = Cint((wholenumber - CInt(wholenumber)) * 100)/100 = CInt(0.1234*100)/100 == 12 / 100 == 0.12

The 3-4th decimals are = wholenumber - CInt(wholenumber*100)/100 = 15.1234 - CInt(1512.34)/100 == 15.1234 - 15.12 == 0.0034

etc...


This is off the top of my head, but you should be able to use string manipulation functions to get the decimals. Something like this...

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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜