decimal 3.2.1 copy "decimal: ^3.2.1" to clipboard
decimal: ^3.2.1 copied to clipboard

The decimal package allows you to deal with decimal numbers without losing precision.

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
copied to clipboard

Usage #

To use this library in your code :

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

Hint : To make your code shorter you can define a shortcut for Decimal.parse :

final d = (String s) => Decimal.parse(s);
d('0.2') + d('0.1'); // => 0.3
copied to clipboard

Formatting with intl #

You can use the intl package to format decimal with DecimalFormat 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 = DecimalFormatter(NumberFormat.decimalPattern('en-US'));
  print(formatter.format(value));
}
copied to clipboard

Tip: you can define an extension to make it more fluent:

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

WARNING: For now (2024.05.30) intl doesn't work with NumberFormat.maximumFractionDigits greater than 15 on web plateform and 18 otherwise.

Parsing with intl #

You can use the NumberFormat from intl package to parse formatted decimals

var currencyFormatter = DecimalFormatter(NumberFormat.simpleCurrency(name: 'USD'));
currencyFormatter.parse('\$3.14'); // => 3.14
copied to clipboard

License #

Apache 2.0

386
likes
160
points
554k
downloads

Publisher

unverified uploader

Weekly Downloads

2024.09.08 - 2025.03.23

The decimal package allows you to deal with decimal numbers without losing precision.

Repository (GitHub)

Documentation

API reference

License

Apache-2.0 (license)

Dependencies

intl, rational

More

Packages that depend on decimal