我想将十进制转换为字符串,看看转换是否成功。
string d;
if (<decimal>d) ....
使用decimal lang-lib中的fromString()
函数,可以将字符串转换为十进制。如果无法转换字符串,将返回一个错误。
如果字符串无法转换为十进制,则可以使用check
表达式返回错误。
function convertToDecimal(string s) returns error?
decimal d = check decimal:fromString("1.234");
io:println(d);
}
如果要手动处理错误,也可以使用联合类型decimal|error
。使用is
运算符检查是否为错误。
function convertToDecimal(string s) {
decimal|error d = decimal:fromString(s);
if(d is decimal) {
// Handle the relevant logic where the decimal conversion is successful.
} else {
// Handle the logic if `d` is an error.
}
}