簡體   English   中英

VB.net:顯示十進制值的某些部分

[英]VB.net: Displaying certain portions of a decimal value

在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字符串格式”之類的Google信息查找大量信息和示例。

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

如果您想發揮創造力並使用基本的簡單操作來完成所有工作,則調用CInt(wholenumber)與Math.floor()相同。 您可以通過乘以10的冪來截斷和移動小數,從而獲得所需的一切。

wholenumber = 15.1234

數字的整數部分= CInt(wholenumber) = 15

小數點= wholenumber - CInt(wholenumber) = 15.1234-15 == 0.1234

前2 = Cint((wholenumber - CInt(wholenumber)) * 100)/100= 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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM