How to convert “0” and “1” to false and true

≡放荡痞女 提交于 2019-12-03 04:08:11

How about:

return (returnValue == "1");

or as suggested below:

return (returnValue != "0");

The correct one will depend on what you are looking for as a success result.

Chris

In a single line of code:

bool bVal = Convert.ToBoolean(Convert.ToInt16(returnValue))

If you want the conversion to always succeed, probably the best way to convert the string would be to consider "1" as true and anything else as false (as Kevin does). If you wanted the conversion to fail if anything other than "1" or "0" is returned, then the following would suffice (you could put it in a helper method):

if (returnValue == "1")
{
    return true;
}
else if (returnValue == "0")
{
    return false;
}
else
{
    throw new FormatException("The string is not a recognized as a valid boolean value.");
}

Set return type to numeric - you don't need a char (so don't use it); a numeric value (0/1) can be converted with Convert.ToBoolean(num)

Otherwise: use Kevin's answer

You can use that form:

return returnValue.Equals("1") ? true : false;

Or more simply (thanks to Jurijs Kastanovs):

return returnValue.Equals("1");

Or if the Boolean value is not been returned, you can do something like this:

bool boolValue = (returnValue == "1");

My solution (vb.net):

Private Function ConvertToBoolean(p1 As Object) As Boolean
    If p1 Is Nothing Then Return False
    If IsDBNull(p1) Then Return False
    If p1.ToString = "1" Then Return True
    If p1.ToString.ToLower = "true" Then Return True
    Return False
End Function
Amin AmiriDarban
(returnValue != "1" ? false : true);

If you don't want to convert.Just use;

 bool _status = status == "1" ? true : false;

Perhaps you will return the values as you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!