2010-12-10 53 views
0

在vb.net中,我想提取wholenumber,decimal,前2個小數位和第3個和第4個小數位。我一直在圍繞解決方案進行盤旋,但並不是那樣。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 " & ????) 

回答

2

你想叫你的數值(目前正在代碼中的隱式調用.ToString()時使用格式說明,但也許應該是明確的)。例如,wholenumber.ToString("##.###")應返回"15.123"

更多信息可以在here找到,大量的信息和例子可以通過谷歌搜索類似「.net字符串格式」來找到。

+0

我最初開始與wholenumber.ToString,但發現它返回.119999999999和.0034000000000000096。對我而言,這不是一個太大的問題,但認爲他們可能是一個更好的方法。儘管如此,謝謝你的提示! – 2010-12-10 20:15:31

+1

@ user538149:這是關於這種情況下的格式字符串。現在,如果您希望實際值被四捨五入,其他提供的答案將更有幫助。但是,如果您只是將_displaying_值指定爲小數位,那麼字符串格式化就是要走的路。 – David 2010-12-10 20:17:16

+0

+1並啓用Option Strict,以便VB不會默默轉換,其危險。 – MarkJ 2010-12-11 08:27:58

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

如果您想創意並使用基本的簡單操作完成所有操作,則調用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(0.1234 * 100)/ 100 ==百分之十二== 0.12

的3-4th小數是= wholenumber - CInt(wholenumber*100)/100 = 15.1234 - CINT(1512.34)/ 100 = = 15.1234 - 15.12 == 0.0034

等等

0

這是從我的頭頂,但你應該能夠使用字符串處理函數來獲得小數。這樣的事情...

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