/dart-decimal

Primary LanguageDartOtherNOASSERTION

Dart Decimals

Build Status

This project enable to make computations on decimal numbers without losing precision like double operations.

For instance :

// with double
print(0.2 + 0.1); // displays 0.30000000000000004

// with decimal
print(Decimal.parse('0.2') + Decimal.parse('0.1')); // displays 0.3

Usage

To use this library in your code :

  • add a dependency in your pubspec.yaml :
dependencies:
  decimal:
  • add import in your dart code :
import 'package:decimal/decimal.dart';
  • Start computing using Decimal.parse('1.23').

  • You can also use toDecimal() extension on num type:

final pointOne = 0.1.toDecimal();
final d = (0.2 + pointOne).toDecimal();

Formatting with intl

You can use the intl package to format decimal by wrapping the decimal into DecimalIntl from the package:decimal/intl.dart library:

import 'package:decimal/decimal.dart';
import 'package:decimal/intl.dart';

main() {
  var value = Decimal.parse('1234.56');
  var formatter = NumberFormat.decimalPattern('en-US');
  print(formatter.format(DecimalIntl(value)));
}

Tip: you can define an extension to make it less verbose:

extension on Decimal {
  String formatWith(NumberFormat formatter) => formatter.format(DecimalIntl(this));
}
main() {
  var value = Decimal.parse('1234.56');
  var formatter = NumberFormat.decimalPattern('en-US');
  print(value.formatWith(formatter));
}

License

Apache 2.0