【问题标题】:Check if string can be converted to a decimal检查字符串是否可以转换为小数
【发布时间】:2022-10-15 15:02:10
【问题描述】:

我想将小数转换为字符串,看看转换是否成功。

string d;
if (<decimal>d) ....

【问题讨论】:

    标签: ballerina


    【解决方案1】:

    使用fromString() function from the decimal lang lib,您可以将字符串转换为小数。如果无法转换字符串,则会返回错误。

    如果字符串无法转换为小数,您可以使用check expression 返回错误。

    function convertToDecimal(string s) returns error?
        decimal d = check decimal:fromString("1.234");
        io:println(d);
    }
    

    或者,如果您想手动处理错误,可以使用联合类型 decimal|error。

    function convertToDecimal(string s) {
        decimal|error d = decimal:fromString(s);
        io:println(d);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 2011-07-26
      • 2010-12-28
      • 2010-10-18
      • 1970-01-01
      • 2012-08-16
      • 2022-09-30
      相关资源
      最近更新 更多