Design float:round langlib function #35589
Replies: 5 comments 2 replies
-
@hasithaa, @gimantha, @MaryamZi, @pcnfernando, @KRVPerera, @chiranSachintha, @suleka96 |
Beta Was this translation helpful? Give feedback.
-
Since we represent ballerina int as long in java, we have to change the type of public static double round(double x, long fractionDigits) {
if (fractionDigits > Integer.MAX_VALUE) {
// As per IEEE, exponent of double value lies from -308 to 307.
// Also, the maximum decimal digits that can have in double value are 15 or 16.
// Therefore, if `fractionDigits` is very large, `x` will not be changed.
return x;
}
// Down cast can be done safely because of above condition.
int fractionDigitsAsInt = (int) fractionDigits;
BigDecimal xInBigDecimal = BigDecimal.valueOf(x);
BigDecimal xTmp = xInBigDecimal;
int digitsTmp = fractionDigitsAsInt;
while (digitsTmp-- > 0) {
if (xTmp.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) == 0) {
return x;
}
xTmp = xTmp.multiply(BigDecimal.TEN);
}
return xInBigDecimal.setScale(fractionDigitsAsInt, RoundingMode.HALF_EVEN).doubleValue();
} |
Beta Was this translation helpful? Give feedback.
-
Please find the progress in PR #35606 |
Beta Was this translation helpful? Give feedback.
-
There is a small correction that I have to do. |
Beta Was this translation helpful? Give feedback.
-
while loops are removed in 3f30ae2 |
Beta Was this translation helpful? Give feedback.
-
Overview
According to spec, we have to implement the following function.
In the current implementation, we do not have
fractionDigits
and we only support rounding to a float without zero decimal places.According to the spec, the result of the rounding operation should be,
10^(-fractionDigits)
Also,
fractionDigits == 0
we can use JavaMath.rint
Implementation Suggestions
Option 1:
Even if the logic is correct this returned error values bacause double operations do not happen as expected.
Option 2:
This method gives the correct output. But there are two drawbacks
fractionDigits == Integer.MAX_VALUE
this throws an exception as shown below.fractionDigits
is close toInteger.MAX_VALUE
, it takes some time to give the output.Because of these drawbacks we have to handle this specially. Please read option 3.
Option 3:
Because of the two drawbacks identified in option 2, we have to add a special calculation.
According to above table we can conculde that if the
fractionDigits
greater than or equal decimal digits ofx
, the output is same asx
. So we can fix above drawbacks using following method.Highly appreciate your input on this, please refer #35543.
Beta Was this translation helpful? Give feedback.
All reactions