Skip to content

Instantly share code, notes, and snippets.

@jack24254029
Last active May 2, 2023 09:09
Show Gist options
  • Save jack24254029/1300963a6be50844e332c059ef27c2c1 to your computer and use it in GitHub Desktop.
Save jack24254029/1300963a6be50844e332c059ef27c2c1 to your computer and use it in GitHub Desktop.
HALF_EVEN of Dart
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();
}
@jack24254029
Copy link
Author

I use the kotlin to verify it.

import java.math.*

fun main() {
    println(BigDecimal(4.5).setScale(0, RoundingMode.HALF_EVEN)) // 4
    println(BigDecimal(3.5).setScale(0, RoundingMode.HALF_EVEN)) // 4
    println(BigDecimal(4.500001).setScale(0, RoundingMode.HALF_EVEN)) // 5
    println(BigDecimal(3.500001).setScale(0, RoundingMode.HALF_EVEN)) // 4
    println("--------")
    println(BigDecimal(-4.5).setScale(0, RoundingMode.HALF_EVEN)) // -4
    println(BigDecimal(-3.5).setScale(0, RoundingMode.HALF_EVEN)) // -4
    println(BigDecimal(-4.500001).setScale(0, RoundingMode.HALF_EVEN)) // -5
    println(BigDecimal(-3.500001).setScale(0, RoundingMode.HALF_EVEN)) // -4
}

@jack24254029
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment