繁体   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