Skip to content

Instantly share code, notes, and snippets.

@hotdang-ca
Last active May 26, 2022 16:52
Show Gist options
  • Save hotdang-ca/3ce3b7deeab231429f50ea6d5d53d356 to your computer and use it in GitHub Desktop.
Save hotdang-ca/3ce3b7deeab231429f50ea6d5d53d356 to your computer and use it in GitHub Desktop.
Dart Double Fun
import 'dart:math';
double roundDouble(double value, double places) {
num mod = pow(10.0, places);
return ((value * mod).round().toDouble() / mod);
}
extension BetterDoubles on num {
num roundAsDoubleBetter(double places) {
final num mod = pow(10.0, places);
return ((this * mod).round().toDouble() / mod);
}
}
void main() {
final num price = 19.99;
// Just the price
print(price);
// * 100, * operator returns a num
print(price * 100);
// roundToDouble includes nearest integer, this won't work
print(price.roundToDouble());
// We need a custom method
print(roundDouble(double.parse(price.toString()), 2));
// multipying but retaining most significant digits
print(roundDouble(double.parse((price * 100).toString()), 2));
// easier way to express the above
final num priceTimes100 = price * 100;
print(roundDouble(double.parse(priceTimes100.toString()), 2));
// even easier way!
print((price * 100).roundAsDoubleBetter(2));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment