Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to an int?

Tags:

ballerina

According to type conversion example a string to int conversion is made with int.convert(). However in Ballerina 1.0.0 that doesn't work:

$ ballerina version
Ballerina 1.0.0
Language specification 2019R3
$ cat test.bal 
public function main() {
    string x = "42";
    int|error y = int.convert(x);
}
$ ballerina build test.bal 
Compiling source
        test.bal
error: .::test.bal:3:19: undefined function 'convert'
$

Also <int> as mentioned elsewhere here in SO doesn't work either:

$ ballerina version
Ballerina 1.0.0
Language specification 2019R3
$ cat test.bal 
public function main() {
    string x = "42";
    int|error y = <int>x;
}
$ ballerina build test.bal 
Compiling source
        test.bal
error: .::test.bal:3:19: incompatible types: 'string' cannot be cast to 'int'
$
like image 982
user272735 Avatar asked Oct 14 '25 15:10

user272735


1 Answers

Ballerina v1.0 and later, you can convert string to int as follows:

import ballerina/lang.'int as langint;

public function main() {
    string x = "42";
    int|error y = langint:fromString(x);
}
like image 95
Chanaka Lakmal Avatar answered Oct 17 '25 06:10

Chanaka Lakmal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!