Last active
May 2, 2023 09:09
-
-
Save jack24254029/1300963a6be50844e332c059ef27c2c1 to your computer and use it in GitHub Desktop.
HALF_EVEN of Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
print(roundHalfEven(4.5)); // 4 | |
print(roundHalfEven(3.5)); // 4 | |
print(roundHalfEven(4.500001)); // 5 | |
print(roundHalfEven(3.500001)); // 4 | |
print('-------'); | |
print(roundHalfEven(-4.5)); //- 4 | |
print(roundHalfEven(-3.5)); //- 4 | |
print(roundHalfEven(-4.500001)); //- 5 | |
print(roundHalfEven(-3.500001)); //- 4 | |
} | |
// Ref: https://cplusplus.com/articles/1UCRko23/ | |
double roundHalfEven(double value, {double epsilon = 0.0000001}) { | |
if (value < 0.0) return -roundHalfEven(-value, epsilon: epsilon); | |
double ipart = value.toInt().toDouble(); | |
// If 'value' is exctly halfway between two integers | |
if ((value - (ipart + 0.5)).abs() < epsilon) { | |
// If 'ipart' is even then return 'ipart' | |
if (ipart % 2.0 < epsilon) { | |
return ipart; | |
} | |
// Else return the nearest even integer | |
return (ipart + 0.5).ceilToDouble(); | |
} | |
// Otherwise use the usual round to closest | |
// (Either symmetric half-up or half-down will do0 | |
return value.roundToDouble(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use the kotlin to verify it.