Int
Float
Decimal
Types
Post
Conversion of Numerical Values
In contrast to certain programming languages, Ballerina does not facilitate implicit conversion among its numerical types. This implies that without explicit conversion, a numerical value cannot be assigned to a variable of a differing numerical type.
Ballerina takes this approach to prevent unintended loss of precision and to safeguard against unexpected program behavior. For instance, when a float
value is assigned to an int
variable, the fractional portion of the float
value will be discarded. Similarly, assigning an int
value to a float
variable converts the value to a float
, introducing a fractional part of zero. While these transformations may not pose a problem when done knowingly, unawareness can lead to unpredictable program behavior. Consequently, Ballerina insists on explicit conversion of numerical values.
Conversion Rules
In the specification, the conversion rules are defined as follows: (See under NumericConvert)
From \ To | float | decimal | int |
---|---|---|---|
float | unchanged | closest math value | round, error for NaN or out of int range |
decimal | closest math value | unchanged | |
int | same math value | same math value | unchanged |
Explicit Conversion
Type Casting
If required, you can use a type-cast expression to do a numeric conversion. This is useful when converting a mapping value to another with the same field name but with a different numerical type.
|
|
bal run numeric_conversion.bal
v1:2
v2:5
v3:10.0
v4:5.0
v5:10.0
v6:2.1
bal version
Ballerina 2201.6.0 (Swan Lake Update 6)
// Partial Code. Change View to see full code.
public function main() {
int intValue = 10;
float floatValue = 2.1;
decimal decimalValue = 5.0;
int v1 = <int>floatValue;
int v2 = <int>decimalValue;
float v3 = <float>intValue;
float v4 = <float>decimalValue;
decimal v5 = <decimal>intValue;
decimal v6 = <decimal>floatValue;
}
// Highlights Only. Change View to see full code.
int intValue = 10;
float floatValue = 2.1;
decimal decimalValue = 5.0;
int v1 = <int>floatValue;
int v2 = <int>decimalValue;
float v3 = <float>intValue;
float v4 = <float>decimalValue;
decimal v5 = <decimal>intValue;
decimal v6 = <decimal>floatValue;
Numeric Conversion
Code Breakdown
- Line 9: This is the same as
<int>f.round(0)
. This uses Ballerina default round-to-nearest rounding mode. It is the same as IEEE roundToIntegralTiesToEven operation. - Line 10: This is the same as
<int>d.round(0)
. This uses Ballerina default round-to-nearest rounding mode. It is the same as IEEE roundToIntegralTiesToEven operation with a minor exception to handling positive exponent.
Using value:cloneWithType()
Another way to convert a numerical value is to use the value:cloneWithType()
function.
🚧 More Details Coming Soon!