簡體   English   中英

在vb.net中將十進制轉換為空字符串

[英]Converting a decimal to an empty string in vb.net

我敢肯定這很簡單,但是我在努力完成這項工作,我嘗試使用convert.tostring,decimal.tostring,ctype(object,type)和cstr(object),但沒有成功。 我想我正在嘗試將專用對象更改為字符串對象,然后為其分配空字符串值,但始終會出現類型不匹配錯誤。

Dim testdecimal as decimal = 0.0
testdecimal = Cstr(testdecimal)
testdecimal = string.empty

您的變量是Decimal
它不能容納字符串。

您需要聲明一個單獨的變量As String來保存字符串。

您不能將小數轉換為空字符串。 我不知道您為什么需要執行上述操作,但是我改用一個object

Dim test As Object = 10.12345
test = "Hi"
test = String.Empty;

看起來您只需要創建數字的字符串表示即可,您可以像這樣進行操作:

'create a decimal variable
Dim testDec As Decimal = 10.12345

'convert decimal to string and then set to empty string
Dim testStr As String = testDec.ToString("N")
testStr = String.Empty

盡管無法將十進制變量的值設置為String.Empty,但是您可以執行以下操作...

Dim TestDecimal As Decimal = 0.0
Dim strStringValue As String = IIf(TestDecimal = 0.0, "", TestDecimal.ToString())
MsgBox(strStringValue)

您的問題是CSTR將值轉換為字符串而不是對象本身,因此您要做的是獲取一個十進制變量,然后將其值轉換為字符串,然后嘗試將字符串放回十進制。

Dim testdecimal as decimal = 0.0 'testDecimal is a decimal type and you are assigning a decimal value
testdecimal = Cstr(testdecimal)  'testDecimal is still a decimal but you are trying to put a string in it Here is your first type mismatch
testdecimal = string.empty   ' If this actually had worked it would have made the above line pointless because you just tried to overwrite the value (even though this line did not execute here is your second type mismatch)

您需要做的是:

Dim NewString as String
Dim testdecimal as decimal = 0.0 
NewString = Cstr(testdecimal) 

上面的代碼使用十進制值並將其轉換為字符串,然后將其存儲到字符串變量中。

現在,對於問題的第二部分,將十進制轉換為空字符串。 這是不可能的,因為0.0轉換為字符串仍然是“ 0.0” string.Empty是“”,它只是一個空字符串。

如果您的意思是如果要將值轉換為0.0,則想將小數轉換為字符串BUT,則可以使用IF語句輕松創建一個空字符串。

基本上只是做:

Dim NewString as String
Dim testdecimal as decimal = 0.0 

if(testdecimal =0.0) Then
NewString = String.Empty
Else
NewString = Cstr(testdecimal) 
END IF

暫無
暫無

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

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