Repository: a14n/dart-decimal
Branch: master
Commit: 3b1e2c813d92
Files: 15
Total size: 64.7 KB
Directory structure:
gitextract_94seb90j/
├── .github/
│ ├── dependabot.yml
│ └── workflows/
│ └── dart.yml
├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── NOTICE
├── README.md
├── analysis_options.yaml
├── example/
│ ├── lib/
│ │ └── example.dart
│ └── pubspec.yaml
├── lib/
│ ├── decimal.dart
│ └── intl.dart
├── pubspec.yaml
└── test/
├── decimal_test.dart
└── intl_test.dart
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/dependabot.yml
================================================
# Set update schedule for GitHub Actions
# See https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/keeping-your-actions-up-to-date-with-dependabot
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
# Check for updates to GitHub Actions every weekday
interval: "weekly"
================================================
FILE: .github/workflows/dart.yml
================================================
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.
name: Dart
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
schedule:
- cron: "0 0 * * 0"
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: dart-lang/setup-dart@v1
- name: Install dependencies
run: dart pub get
- name: Verify formatting
run: dart format --output=none --set-exit-if-changed .
- name: Analyze project source
run: dart analyze --fatal-warnings --fatal-infos
- name: Run VM tests
run: dart test --platform vm
- name: Run Chrome tests
run: dart test --platform chrome
================================================
FILE: .gitignore
================================================
packages
.packages
pubspec.lock
.pub/
.dart_tool
build/
================================================
FILE: CHANGELOG.md
================================================
# 3.2.4 (2025-06-22)
- Fix issue with scale of zero causing problem in addition/substraction with zero.
# 3.2.3 (2025-06-19)
- Fix bad scale value by parsing `0.0` (see [Issue with Decimal.tryParse return value formatting](https://github.com/a14n/dart-decimal/issues/115))
# 3.2.2 (2025-06-15)
- loosen `intl` to `>=0.19.0 <0.21.0` to address [Intl version within flutter_localizations makes version 3.2.1 of decimal impossible to use on Flutter v3.29.3](https://github.com/a14n/dart-decimal/issues/113)
- Bump `lints` to 5.0.0
- [Make `Decimal.zero`, `Decimal.one`, and `Decimal.ten` final](https://github.com/a14n/dart-decimal/pull/114)
# 3.2.1 (2025-01-20)
- [fix: toString() method for values < 0.1](https://github.com/a14n/dart-decimal/pull/111)
# 3.2.0 (2025-01-19)
- Improve performances
# 3.1.0 (2024-11-22)
- Bump `intl` to 0.20.0, `lints` to 5.0.0
- Bump SDK to 3.3.0 (enables wasm)
# 3.0.2 (2024-06-09)
- Fix #107: avoid exception when formatting decimal with `NumberFormat.compact()`.
# 3.0.1 (2024-06-04)
- Throw `FormatException` on `formatter.parse('NaN')`.
# 3.0.0 (2024-06-02)
- Add `DecimalFormatter` to deal with [intl](https://pub.dev/packages/intl) package. Your can now parse and format decimals.
- Add a dependency to intl.
# 2.3.3 (2023-07-08)
- [Introduce logical operators to DecimalIntl to support intl 0.18.0](https://github.com/a14n/dart-decimal/pull/98)
# 2.3.2 (2022-12-07)
- Update files according to license.
# 2.3.1 (2022-11-24)
- Update license file to be recognized by pub.dev.
# 2.3.0 (2022-09-07)
- (Breaking change) Fix `Decimal.pow` return type. This method now returns a `Rational` because `3.pow(-1)` (similar to `1/3`) could not be represented as a `Decimal`.
- Allow `Rational.toDecimal()` customization via its new `toBigInt` parameter.
# 2.2.0 (2022-04-19)
- Fix [toStringAsExponential returned 10.00e+7 instead of 1.00e+8](https://github.com/a14n/dart-decimal/issues/74)
# 2.1.0 (2021-12-22)
- Fix [toStringAsExponential returns INFINITY](https://github.com/a14n/dart-decimal/issues/48) by implementing `toStringAsExponential` without relying on double implementation.
- Fix issue to have `zero.precision == 1`.
# 2.0.1 (2021-12-20)
- Fix [`toString` issue with negative number between 0 and -1](https://github.com/a14n/dart-decimal/issues/65)
# 2.0.0 (2021-11-29)
The goal of this version is to have sharper types on the API and to avoid having [Decimal] objects that are not decimal numbers (`1/3` for instance).
It introduces several breaking changes.
- `~/` now returns a `BigInt`. If you need a `Decimal` you can convert the `BigInt` to `Decimal` with `bigint.toDecimal()`.
- Removal of `isNaN` getter. It was always returning `false`.
- Removal of `isInfinite` getter. It was always returning `false`.
- Removal of `isNegative` getter. You can replace it with `decimal < Decimal.zero`.
- `inverse`, `/` now return a `Rational`. If you need a `Decimal` you can convert the `Rational` to `Decimal` with `rational.toDecimal(scaleOnInfinitePrecision: xxx)`. If you need to make several computations where inverses or divisions are involved you should make thoses operations on `Rational` type to avoid loosing precision and at the end convert the result back to `Decimal` if you want to display the result in a decimal form.
Other changes:
- `round()`, `floor()`, `ceil()`, `truncate()` now accept an optional `scale` to indicate at which digit the operation should be done.
- Add `shift` to move the decimal point.
- Add extension method `hasFinitePrecision` on `Rational` to know if a decimal form of the rational is possible without loosing precision.
- Add extension method `toDecimal()` on `Rational`.
- Add extension method `toDecimal()` on `int`.
- Add extension method `toDecimal()` on `BigInt`.
# 1.5.0 (2021-11-17)
- Support json serialization as String with `Decimal.fromJson`/`Decimal.toJson`.
# 1.4.0 (2021-11-16)
- Add `Decimal.ten`.
- Add `Decimal.toBigInt`.
# 1.3.0 (2021-07-21)
- Add `Decimal.fromBigInt`.
# 1.2.0 (2021-05-31)
- Add `DecimalIntl` to allow formatting with [intl](https://pub.dev/packages/intl) package.
# 1.1.0 (2021-04-29)
- Allow negative value as exponent of `pow`.
# 1.0.0+1 (2021-03-29)
- Fix typo in the description of the package.
# 1.0.0 (2021-02-25)
- Stable null safety release.
# 1.0.0-nullsafety (2020-11-27)
- Migrate to nullsafety.
# 0.3.5 (2019-09-02)
- [add `Decimal.pow`](https://github.com/a14n/dart-decimal/issues/24).
# 0.3.4 (2019-07-29)
- add `Decimal.zero` and `Decimal.one`.
- add `Decimal.inverse`.
# 0.3.3 (2019-01-16)
- add `Decimal.tryParse`.
# 0.3.2 (2018-07-24)
- migration to Dart 2.
# v0.3.1 (2018-07-10)
- make `Decimal.parse` a factory constructor.
# v0.3.0 (2018-07-10)
- allow parsing of `1.`
# v0.2.0 (2018-04-15)
- move to Dart SDK 2.0
# v0.1.4 (2017-06-16)
- make package strong clean
# v0.1.3 (2014-10-29)
- add `Decimal.signum`
- add `Decimal.hasFinitePrecision`
- add `Decimal.precision`
- add `Decimal.scale`
# Semantic Version Conventions
http://semver.org/
- *Stable*: All even numbered minor versions are considered API stable:
i.e.: v1.0.x, v1.2.x, and so on.
- *Development*: All odd numbered minor versions are considered API unstable:
i.e.: v0.9.x, v1.1.x, and so on.
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: NOTICE
================================================
Copyright 2013 Alexandre Ardhuin
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# Dart Decimals
[](https://github.com/a14n/dart-decimal/actions/workflows/dart.yml)
This project enable to make computations on decimal numbers without losing precision like double operations.
For instance :
```dart
// 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` :
```yaml
dependencies:
decimal:
```
* add import in your `dart` code :
```dart
import 'package:decimal/decimal.dart';
```
* Start computing using `Decimal.parse('1.23')`.
_Hint_ : To make your code shorter you can define a shortcut for Decimal.parse :
```dart
final d = (String s) => Decimal.parse(s);
d('0.2') + d('0.1'); // => 0.3
```
## Formatting with intl
You can use the [intl](https://pub.dev/packages/intl) package to format decimal
with `DecimalFormat` from the `package:decimal/intl.dart` library:
```dart
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));
}
```
Tip: you can define an extension to make it more fluent:
```dart
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));
}
```
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](https://pub.dev/packages/intl) package to parse formatted decimals
```dart
var currencyFormatter = DecimalFormatter(NumberFormat.simpleCurrency(name: 'USD'));
currencyFormatter.parse('\$3.14'); // => 3.14
```
## License
Apache 2.0
================================================
FILE: analysis_options.yaml
================================================
include: package:lints/recommended.yaml
analyzer:
language:
strict-casts: true
strict-inference: true
strict-raw-types: true
linter:
rules:
- prefer_single_quotes
================================================
FILE: example/lib/example.dart
================================================
import 'package:decimal/decimal.dart';
void main() {
print(Decimal.parse('0.1') + Decimal.parse('0.2'));
}
================================================
FILE: example/pubspec.yaml
================================================
name: decimal_example
version: 0.0.1
description: Example app for the decimal package.
homepage: https://github.com/a14n/dart-decimal
environment:
sdk: ">=2.12.0 <3.0.0"
publish_to: none
dependencies:
decimal:
path: ../
================================================
FILE: lib/decimal.dart
================================================
// Copyright 2013 Alexandre Ardhuin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'dart:math';
import 'package:rational/rational.dart';
final _i0 = BigInt.zero;
final _i1 = BigInt.one;
final _i2 = BigInt.two;
final _i5 = BigInt.from(5);
final _i10 = BigInt.from(10);
final _r10 = Rational.fromInt(10);
/// A number that can be exactly written with a finite number of digits in the
/// decimal system.
class Decimal implements Comparable<Decimal> {
Decimal._(this._value, this._scale);
/// Create a new [Decimal] from a [BigInt].
factory Decimal.fromBigInt(BigInt value) => Decimal._(value, 0);
/// Create a new [Decimal] from an [int].
factory Decimal.fromInt(int value) => Decimal.fromBigInt(BigInt.from(value));
/// Create a new [Decimal] from its [String] representation.
factory Decimal.fromJson(String value) => Decimal.parse(value);
final BigInt _value;
final int _scale;
late final Rational _rational = _scale > 0
? Rational(_value, _i10.pow(_scale))
: Rational(_value * _i10.pow(_scale.abs()));
static final _pattern =
RegExp(r'^([+-]?\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$');
/// Parses [source] as a decimal literal and returns its value as [Decimal].
static Decimal parse(String source) {
final match = _pattern.firstMatch(source);
if (match == null) {
throw FormatException('$source is not a valid format');
}
final group1 = match.group(1);
final group2 = match.group(2) ?? '';
final group3 = match.group(3);
var value = BigInt.parse('$group1$group2');
var scale = group3 == null ? 0 : -int.parse(group3);
scale += group2.length;
return Decimal._(value, scale);
}
/// Parses [source] as a decimal literal and returns its value as [Decimal], or null if the parsing fails.
static Decimal? tryParse(String source) {
try {
return Decimal.parse(source);
} on FormatException {
return null;
}
}
/// The [Decimal] corresponding to `0`.
static final zero = Decimal.fromInt(0);
/// The [Decimal] corresponding to `1`.
static final one = Decimal.fromInt(1);
/// The [Decimal] corresponding to `10`.
static final ten = Decimal.fromInt(10);
/// The [Rational] corresponding to `this`.
Rational toRational() => _rational;
/// Returns `true` if `this` is an integer.
bool get isInteger => _scale <= 0 || _rescaled._scale <= 0;
/// Returns a [Rational] corresponding to `1/this`.
Rational get inverse => _rational.inverse;
@override
bool operator ==(Object other) => other is Decimal && compareTo(other) == 0;
@override
int get hashCode => Object.hash(_rescaled._value, _rescaled._scale);
/// Returns a [String] representation of `this`.
@override
String toString() {
var d = _rescaled;
var v = d._value.abs().toString();
var s = d._scale;
if (s <= 0) {
v = v + '0' * -s;
} else if (v.length <= s) {
v = '0.${'0' * (s - v.length)}$v';
} else {
v = '${v.substring(0, v.length - s)}.${v.substring(v.length - s)}';
}
if (_value.isNegative) v = '-$v';
return v;
}
/// Converts `this` to [String] by using [toString].
String toJson() => toString();
@override
int compareTo(Decimal other) {
var (d1, d2) = _unifyScale(this, other);
return d1._value.compareTo(d2._value);
}
/// Addition operator.
Decimal operator +(Decimal other) {
var (d1, d2) = _unifyScale(this, other);
return Decimal._(d1._value + d2._value, d1._scale);
}
/// Subtraction operator.
Decimal operator -(Decimal other) => this + (-other);
/// Multiplication operator.
Decimal operator *(Decimal other) =>
Decimal._(_value * other._value, _scale + other._scale);
/// Euclidean modulo operator.
///
/// See [num.operator%].
Decimal operator %(Decimal other) {
var (d1, d2) = _unifyScale(this, other);
return Decimal._(d1._value % d2._value, d1._scale);
}
/// Division operator.
Rational operator /(Decimal other) => _rational / other._rational;
/// Truncating division operator.
///
/// See [num.operator~/].
BigInt operator ~/(Decimal other) {
var (d1, d2) = _unifyScale(this, other);
return d1._value ~/ d2._value;
}
/// Returns the negative value of this rational.
Decimal operator -() => Decimal._(-_value, _scale);
/// Return the remainder from dividing this [Decimal] by [other].
Decimal remainder(Decimal other) {
var (d1, d2) = _unifyScale(this, other);
return Decimal._(d1._value.remainder(d2._value), d1._scale);
}
/// Whether this number is numerically smaller than [other].
bool operator <(Decimal other) => compareTo(other) < 0;
/// Whether this number is numerically smaller than or equal to [other].
bool operator <=(Decimal other) => compareTo(other) <= 0;
/// Whether this number is numerically greater than [other].
bool operator >(Decimal other) => compareTo(other) > 0;
/// Whether this number is numerically greater than or equal to [other].
bool operator >=(Decimal other) => compareTo(other) >= 0;
/// Returns the absolute value of `this`.
Decimal abs() => Decimal._(_value.abs(), _scale);
/// The signum function value of `this`.
///
/// E.e. -1, 0 or 1 as the value of this [Decimal] is negative, zero or positive.
int get sign => _value.sign;
@Deprecated('Use .sign')
int get signum => _value.sign;
/// Returns the greatest [Decimal] value no greater than this [Decimal].
///
/// An optional [scale] value can be provided as parameter to indicate the
/// digit used as reference for the operation.
///
/// ```
/// var x = Decimal.parse('123.4567');
/// x.floor(); // 123
/// x.floor(scale: 1); // 123.4
/// x.floor(scale: 2); // 123.45
/// x.floor(scale: -1); // 120
/// ```
Decimal floor({int scale = 0}) => _scaleAndApply(scale, (e) => e.floor());
/// Returns the least [Decimal] value that is no smaller than this [Decimal].
///
/// An optional [scale] value can be provided as parameter to indicate the
/// digit used as reference for the operation.
///
/// ```
/// var x = Decimal.parse('123.4567');
/// x.ceil(); // 124
/// x.ceil(scale: 1); // 123.5
/// x.ceil(scale: 2); // 123.46
/// x.ceil(scale: -1); // 130
/// ```
Decimal ceil({int scale = 0}) => _scaleAndApply(scale, (e) => e.ceil());
/// Returns the [Decimal] value closest to this number.
///
/// Rounds away from zero when there is no closest integer:
/// `(3.5).round() == 4` and `(-3.5).round() == -4`.
///
/// An optional [scale] value can be provided as parameter to indicate the
/// digit used as reference for the operation.
///
/// ```
/// var x = Decimal.parse('123.4567');
/// x.round(); // 123
/// x.round(scale: 1); // 123.5
/// x.round(scale: 2); // 123.46
/// x.round(scale: -1); // 120
/// ```
Decimal round({int scale = 0}) => _scaleAndApply(scale, (e) => e.round());
Decimal _scaleAndApply(int scale, BigInt Function(Rational) f) {
final scaleFactor = ten.pow(scale);
return (f(_rational * scaleFactor).toRational() / scaleFactor).toDecimal();
}
/// The [BigInt] obtained by discarding any fractional digits from `this`.
Decimal truncate({int scale = 0}) =>
_scaleAndApply(scale, (e) => e.truncate());
/// Shift the decimal point on the right for positive [value] or on the left
/// for negative one.
///
/// ```dart
/// var x = Decimal.parse('123.4567');
/// x.shift(1); // 1234.567
/// x.shift(-1); // 12.34567
/// ```
Decimal shift(int value) => Decimal._(_value, _scale - value);
/// Clamps `this` to be in the range [lowerLimit]-[upperLimit].
Decimal clamp(Decimal lowerLimit, Decimal upperLimit) => this < lowerLimit
? lowerLimit
: this > upperLimit
? upperLimit
: this;
/// The [BigInt] obtained by discarding any fractional digits from `this`.
BigInt toBigInt() => switch (this) {
var d when d._scale > 0 => d._value ~/ _i10.pow(d._scale),
var d when d._scale < 0 => d._value * _i10.pow(-d._scale),
var d => d._value,
};
/// Returns `this` as a [double].
///
/// If the number is not representable as a [double], an approximation is
/// returned. For numerically large integers, the approximation may be
/// infinite.
double toDouble() => switch (this) {
var d when d._scale > 0 => d._value / _i10.pow(d._scale),
var d when d._scale < 0 => (d._value * _i10.pow(-d._scale)).toDouble(),
var d => d._value.toDouble(),
};
/// The precision of this [Decimal].
///
/// The precision is the number of digits in the unscaled value.
///
/// ```dart
/// Decimal.parse('0').precision; // => 1
/// Decimal.parse('1').precision; // => 1
/// Decimal.parse('1.5').precision; // => 2
/// Decimal.parse('0.5').precision; // => 2
/// ```
int get precision {
final value = abs();
return value.scale + value.toBigInt().toString().length;
}
/// The scale of this [Decimal].
///
/// The scale is the number of digits after the decimal point.
///
/// ```dart
/// Decimal.parse('1.5').scale; // => 1
/// Decimal.parse('1').scale; // => 0
/// ```
int get scale => _scale <= 0 ? 0 : max(_rescaled._scale, 0);
/// A decimal-point string-representation of this number with [fractionDigits]
/// digits after the decimal point.
String toStringAsFixed(int fractionDigits) {
assert(fractionDigits >= 0);
if (fractionDigits == 0) return round().toBigInt().toString();
final value = round(scale: fractionDigits);
final intPart = value.toBigInt().abs();
final decimalPart =
(one + value.abs() - intPart.toDecimal()).shift(fractionDigits);
return '${value < zero ? '-' : ''}$intPart.${decimalPart.toString().substring(1)}';
}
/// An exponential string-representation of this number with [fractionDigits]
/// digits after the decimal point.
String toStringAsExponential([int fractionDigits = 0]) {
assert(fractionDigits >= 0);
final negative = this < zero;
var value = abs();
var eValue = 0;
while (value < one && value > zero) {
value *= ten;
eValue--;
}
while (value >= ten) {
value = (value / ten).toDecimal();
eValue++;
}
value = value.round(scale: fractionDigits);
// If the rounded value is 10, then divide it once more to make it follow
// the normalized scientific notation. See https://github.com/a14n/dart-decimal/issues/74
if (value == ten) {
value = (value / ten).toDecimal();
eValue++;
}
return <String>[
if (negative) '-',
value.toStringAsFixed(fractionDigits),
'e',
if (eValue >= 0) '+',
'$eValue',
].join();
}
/// A string representation with [precision] significant digits.
String toStringAsPrecision(int precision) {
assert(precision > 0);
if (this == zero) {
return <String>[
'0',
if (precision > 1) '.',
for (var i = 1; i < precision; i++) '0',
].join();
}
final limit = ten.pow(precision).toDecimal();
var shift = one;
final absValue = abs();
var pad = 0;
while (absValue * shift < limit) {
pad++;
shift *= ten;
}
while (absValue * shift >= limit) {
pad--;
shift = (shift / ten).toDecimal();
}
final value = ((this * shift).round() / shift).toDecimal();
return pad <= 0 ? value.toString() : value.toStringAsFixed(pad);
}
/// Returns `this` to the power of [exponent].
///
/// Returns [Rational.one] if the [exponent] equals `0`.
Rational pow(int exponent) => _rational.pow(exponent);
static (Decimal, Decimal) _unifyScale(Decimal d1, Decimal d2) {
var s1 = d1._scale;
var s2 = d2._scale;
return switch (null) {
_ when s1 > s2 => (d1, Decimal._(d2._value * _i10.pow(s1 - s2), s1)),
_ when s1 < s2 => (Decimal._(d1._value * _i10.pow(s2 - s1), s2), d2),
_ => (d1, d2),
};
}
late final Decimal _rescaled = () {
if (this == Decimal.zero) return Decimal.zero;
var d = this;
while (true) {
if (d._value % _i10 == _i0) {
d = Decimal._(d._value ~/ _i10, d._scale - 1);
} else {
break;
}
}
return d;
}();
}
/// Extensions on [Rational].
extension RationalExt on Rational {
/// Returns a [Decimal] corresponding to `this`.
///
/// Some rational like `1/3` can not be converted to decimal because they need
/// an infinite number of digits. For those cases (where [hasFinitePrecision]
/// is `false`) a [scaleOnInfinitePrecision] and a [toBigInt] can be provided
/// to convert `this` to a [Decimal] representation. By default [toBigInt]
/// use [Rational.truncate] to limit the number of digit.
///
/// Note that the returned decimal will not be exactly equal to `this`.
Decimal toDecimal({
int? scaleOnInfinitePrecision,
BigInt Function(Rational)? toBigInt,
}) {
if (hasFinitePrecision) {
var scale = _scale;
return Decimal._((this * Rational(_i10.pow(scale))).toBigInt(), scale);
}
if (scaleOnInfinitePrecision == null) {
throw AssertionError(
'scaleOnInfinitePrecision is required for rationale without finite precision');
}
final scaleFactor = _r10.pow(scaleOnInfinitePrecision);
toBigInt ??= (value) => value.truncate();
return Decimal._(toBigInt(this * scaleFactor), scaleOnInfinitePrecision);
}
/// Returns `true` if this [Rational] has a finite precision.
///
/// Having a finite precision means that the number can be exactly represented
/// as decimal with a finite number of fractional digits.
bool get hasFinitePrecision {
// the denominator should only be a product of powers of 2 and 5
var den = denominator;
while (den % _i5 == _i0) {
den = den ~/ _i5;
}
while (den % _i2 == _i0) {
den = den ~/ _i2;
}
return den == _i1;
}
/// The scale of this [Rational].
///
/// The scale is the number of digits after the decimal point.
///
/// ```dart
/// Decimal.parse('1.5').scale; // => 1
/// Decimal.parse('1').scale; // => 0
/// ```
int get _scale {
var i = 0;
var x = this;
while (!x.isInteger) {
i++;
x *= _r10;
}
return i;
}
}
/// Extensions on [BigInt].
extension BigIntExt on BigInt {
/// This [BigInt] as a [Decimal].
Decimal toDecimal() => Decimal.fromBigInt(this);
}
/// Extensions on [int].
extension IntExt on int {
/// This [int] as a [Decimal].
Decimal toDecimal() => Decimal.fromInt(this);
}
================================================
FILE: lib/intl.dart
================================================
// Copyright 2013 Alexandre Ardhuin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:decimal/decimal.dart';
import 'package:intl/intl.dart';
import 'package:rational/rational.dart';
class DecimalFormatter {
DecimalFormatter(this.numberFormat);
final NumberFormat numberFormat;
/// Parses [text] as a decimal literal using the provided number formatter and returns its value as [Decimal]
Decimal parse(String text) =>
_DartDecimalNumberParser(numberFormat, text).value!;
/// Parses [text] as a decimal literal using the provided number formatter and returns its value as [Decimal], or null if the parsing fails.
Decimal? tryParse(String text) {
try {
return parse(text);
} on FormatException {
return null;
}
}
/// Format [number] according to our pattern and return the formatted string.
String format(Decimal number) => numberFormat.format(_DecimalIntl(number));
}
class _DecimalIntl {
_DecimalIntl(Decimal decimal) : this._rational(decimal.toRational());
_DecimalIntl._rational(this._rational);
factory _DecimalIntl._(dynamic number) {
if (number is _DecimalIntl) {
return number;
} else if (number is Decimal) {
return _DecimalIntl(number);
} else if (number is Rational) {
return _DecimalIntl._rational(number);
} else if (number is BigInt) {
return _DecimalIntl(Decimal.fromBigInt(number));
} else if (number is int) {
return _DecimalIntl(Decimal.fromInt(number));
}
return _DecimalIntl(Decimal.parse(number.toString()));
}
final Rational _rational;
bool get isNegative => _rational < Rational.zero;
_DecimalIntl abs() => _DecimalIntl._rational(_rational.abs());
_DecimalIntl operator ~/(dynamic other) =>
_DecimalIntl._(_rational ~/ _DecimalIntl._(other)._rational);
_DecimalIntl operator +(dynamic other) =>
_DecimalIntl._(_rational + _DecimalIntl._(other)._rational);
_DecimalIntl operator -(dynamic other) =>
_DecimalIntl._(_rational - _DecimalIntl._(other)._rational);
_DecimalIntl operator *(dynamic other) =>
_DecimalIntl._(_rational * _DecimalIntl._(other)._rational);
num operator /(dynamic other) =>
(_rational / _DecimalIntl._(other)._rational).toDouble();
bool operator <(dynamic other) => _rational < _DecimalIntl._(other)._rational;
bool operator <=(dynamic other) =>
_rational <= _DecimalIntl._(other)._rational;
bool operator >(dynamic other) => _rational > _DecimalIntl._(other)._rational;
bool operator >=(dynamic other) =>
_rational >= _DecimalIntl._(other)._rational;
_DecimalIntl remainder(dynamic other) =>
_DecimalIntl._(_rational.remainder(_DecimalIntl._(other)._rational));
int toInt() => _rational.toBigInt().toInt();
double toDouble() => _rational.toDouble();
_DecimalIntl round() => _DecimalIntl._(_rational.round());
@override
bool operator ==(Object other) =>
_rational == _DecimalIntl._(other)._rational;
@override
int get hashCode => _rational.hashCode;
@override
String toString() => _rational.toString();
}
class _DartDecimalNumberParser extends NumberParserBase<Decimal> {
_DartDecimalNumberParser(super.format, super.text);
@override
Decimal fromNormalized(String normalizedText) =>
Decimal.parse(normalizedText);
@override
Decimal nan() => throw FormatException('Could not parse Decimal');
@override
Decimal negativeInfinity() =>
throw FormatException('Could not parse Decimal');
@override
Decimal positiveInfinity() =>
throw FormatException('Could not parse Decimal');
@override
Decimal scaled(Decimal parsed, int scale) => (parsed / Decimal.fromInt(scale))
.toDecimal(scaleOnInfinitePrecision: scale);
}
================================================
FILE: pubspec.yaml
================================================
name: decimal
version: 3.2.4
description: >
The decimal package allows you to deal with decimal numbers without losing
precision.
repository: https://github.com/a14n/dart-decimal
environment:
sdk: ">=3.3.0 <4.0.0"
dependencies:
intl: ">=0.19.0 <0.21.0"
rational: ^2.0.0
dev_dependencies:
expector: ^0.1.4
lints: 6.0.0
test: ^1.25.4
================================================
FILE: test/decimal_test.dart
================================================
// Copyright 2013 Alexandre Ardhuin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'dart:convert';
import 'package:decimal/decimal.dart';
import 'package:expector/expector.dart';
import 'package:rational/rational.dart';
import 'package:test/test.dart' show group, test;
Decimal dec(String value) => Decimal.parse(value);
void main() {
test('tryParse', () {
expectThat(Decimal.tryParse('1')).equals(dec('1'));
expectThat(Decimal.tryParse('a')).isNull;
});
test('string validation', () async {
await expectThat(() => dec('1')).returnsNormally();
await expectThat(() => dec('-1')).returnsNormally();
await expectThat(() => dec('1.')).returnsNormally();
await expectThat(() => dec('1.0')).returnsNormally();
});
test('get isInteger', () {
expectThat(dec('1').isInteger).isTrue;
expectThat(dec('0').isInteger).isTrue;
expectThat(dec('-1').isInteger).isTrue;
expectThat(dec('-1.0').isInteger).isTrue;
expectThat(dec('1.2').isInteger).isFalse;
expectThat(dec('-1.21').isInteger).isFalse;
expectThat(dec('1.00000').isInteger).isTrue;
expectThat(dec('-1.00000').isInteger).isTrue;
});
test('get inverse', () {
expectThat(dec('1').inverse).equals(dec('1').toRational());
expectThat(dec('0.1').inverse).equals(dec('10').toRational());
expectThat(dec('200').inverse).equals(dec('0.005').toRational());
});
test('operator ==(Decimal other)', () {
expectThat(dec('1') == dec('1')).isTrue;
expectThat(dec('1') == dec('2')).isFalse;
expectThat(dec('1') == dec('1.0')).isTrue;
expectThat(dec('1') == dec('2.0')).isFalse;
expectThat(dec('1') != dec('1')).isFalse;
expectThat(dec('1') != dec('2')).isTrue;
});
test('toString()', () {
for (final n in [
'0',
'1',
'-0.1',
'-1',
'-1.1',
'23',
'31878018903828899277492024491376690701584023926880.1',
'0.05'
]) {
expectThat(dec(n).toString()).equals(n);
}
expectThat(dec('0.000').toString()).equals('0');
expectThat(dec('-0.000').toString()).equals('0');
expectThat((dec('1.2') - dec('1.2')).toString()).equals('0');
expectThat(dec('1.000').toString()).equals('1');
expectThat(dec('-1.000').toString()).equals('-1');
expectThat((dec('1') / dec('3')).toString()).equals('1/3');
expectThat(dec('9.9').toString()).equals('9.9');
expectThat((dec('1.0000000000000000000000000000000000000000000000001') *
dec('1.0000000000000000000000000000000000000000000000001'))
.toString())
.equals(
'1.00000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000001');
expectThat(dec('0.0500').toString()).equals('0.05');
});
test('compareTo(Decimal other)', () {
expectThat(dec('1').compareTo(dec('1'))).equals(0);
expectThat(dec('1').compareTo(dec('1.0'))).equals(0);
expectThat(dec('1').compareTo(dec('1.1'))).equals(-1);
expectThat(dec('1').compareTo(dec('0.9'))).equals(1);
});
test('operator +(Decimal other)', () {
expectThat(dec('1') + dec('1')).equals(dec('2'));
expectThat(dec('1.1') + dec('1')).equals(dec('2.1'));
expectThat(dec('1.1') + dec('0.9')).equals(dec('2'));
expectThat(dec('31878018903828899277492024491376690701584023926880.0') +
dec('0.9'))
.equals(dec('31878018903828899277492024491376690701584023926880.9'));
expectThat(dec('0.000325') + dec('0')).equals(dec('0.000325'));
expectThat(dec('0') + dec('0.000325')).equals(dec('0.000325'));
expectThat(dec('0.000325') + Decimal.zero).equals(dec('0.000325'));
expectThat(Decimal.zero + dec('0.000325')).equals(dec('0.000325'));
expectThat(dec('0.000325') + dec('0.0000000000')).equals(dec('0.000325'));
expectThat(dec('0.0000000000') + dec('0.000325')).equals(dec('0.000325'));
});
test('operator -(Decimal other)', () {
expectThat(dec('1') - dec('1')).equals(dec('0'));
expectThat(dec('1.1') - dec('1')).equals(dec('0.1'));
expectThat(dec('0.1') - dec('1.1')).equals(dec('-1'));
expectThat(dec('31878018903828899277492024491376690701584023926880.0') -
dec('0.9'))
.equals(dec('31878018903828899277492024491376690701584023926879.1'));
});
test('operator *(Decimal other)', () {
expectThat(dec('1') * dec('1')).equals(dec('1'));
expectThat(dec('1.1') * dec('1')).equals(dec('1.1'));
expectThat(dec('1.1') * dec('0.1')).equals(dec('0.11'));
expectThat(dec('1.1') * dec('0')).equals(dec('0'));
expectThat(dec('31878018903828899277492024491376690701584023926880.0') *
dec('10'))
.equals(dec('318780189038288992774920244913766907015840239268800'));
});
test('operator %(Decimal other)', () {
expectThat(dec('2') % dec('1')).equals(dec('0'));
expectThat(dec('0') % dec('1')).equals(dec('0'));
expectThat(dec('8.9') % dec('1.1')).equals(dec('0.1'));
expectThat(dec('-1.2') % dec('0.5')).equals(dec('0.3'));
expectThat(dec('-1.2') % dec('-0.5')).equals(dec('0.3'));
expectThat(dec('1e1') % dec('0.3')).equals(dec('0.1'));
expectThat(dec('0.3') % dec('1e1')).equals(dec('0.3'));
});
test('operator /(Decimal other)', () async {
await expectThat(() => dec('1') / dec('0')).throws;
expectThat(dec('1') / dec('1')).equals(dec('1').toRational());
expectThat(dec('1.1') / dec('1')).equals(dec('1.1').toRational());
expectThat(dec('1.1') / dec('0.1')).equals(dec('11').toRational());
expectThat(dec('0') / dec('0.2315')).equals(dec('0').toRational());
expectThat(dec('31878018903828899277492024491376690701584023926880.0') /
dec('10'))
.equals(dec('3187801890382889927749202449137669070158402392688')
.toRational());
});
test('operator ~/(Decimal other)', () async {
await expectThat(() => dec('1') ~/ dec('0')).throws;
expectThat(dec('3') ~/ dec('2')).equals(BigInt.from(1));
expectThat(dec('1.1') ~/ dec('1')).equals(BigInt.from(1));
expectThat(dec('1.1') ~/ dec('0.1')).equals(BigInt.from(11));
expectThat(dec('0') ~/ dec('0.2315')).equals(BigInt.from(0));
});
test('operator -()', () {
expectThat(-dec('1')).equals(dec('-1'));
expectThat(-dec('-1')).equals(dec('1'));
});
test('remainder(Decimal other)', () {
expectThat(dec('2').remainder(dec('1'))).equals(dec('0'));
expectThat(dec('0').remainder(dec('1'))).equals(dec('0'));
expectThat(dec('8.9').remainder(dec('1.1'))).equals(dec('0.1'));
expectThat(dec('-1.2').remainder(dec('0.5'))).equals(dec('-0.2'));
expectThat(dec('-1.2').remainder(dec('-0.5'))).equals(dec('-0.2'));
});
test('operator <(Decimal other)', () {
expectThat(dec('1') < dec('1')).isFalse;
expectThat(dec('1') < dec('1.0')).isFalse;
expectThat(dec('1') < dec('1.1')).isTrue;
expectThat(dec('1') < dec('0.9')).isFalse;
});
test('operator <=(Decimal other)', () {
expectThat(dec('1') <= dec('1')).isTrue;
expectThat(dec('1') <= dec('1.0')).isTrue;
expectThat(dec('1') <= dec('1.1')).isTrue;
expectThat(dec('1') <= dec('0.9')).isFalse;
});
test('operator >(Decimal other)', () {
expectThat(dec('1') > dec('1')).isFalse;
expectThat(dec('1') > dec('1.0')).isFalse;
expectThat(dec('1') > dec('1.1')).isFalse;
expectThat(dec('1') > dec('0.9')).isTrue;
});
test('operator >=(Decimal other)', () {
expectThat(dec('1') >= dec('1')).isTrue;
expectThat(dec('1') >= dec('1.0')).isTrue;
expectThat(dec('1') >= dec('1.1')).isFalse;
expectThat(dec('1') >= dec('0.9')).isTrue;
});
test('abs()', () {
expectThat(dec('-1.49').abs()).equals(dec('1.49'));
expectThat(dec('1.498').abs()).equals(dec('1.498'));
});
test('signum', () {
expectThat(dec('-1.49').sign).equals(-1);
expectThat(dec('1.49').sign).equals(1);
expectThat(dec('0').sign).equals(0);
});
group('floor()', () {
test('without scale', () {
expectThat(dec('1').floor()).equals(dec('1'));
expectThat(dec('-1').floor()).equals(dec('-1'));
expectThat(dec('1.49').floor()).equals(dec('1'));
expectThat(dec('-1.49').floor()).equals(dec('-2'));
});
test('with positive scale', () {
expectThat(dec('1').floor(scale: 1)).equals(dec('1'));
expectThat(dec('-1').floor(scale: 1)).equals(dec('-1'));
expectThat(dec('1.49').floor(scale: 1)).equals(dec('1.4'));
expectThat(dec('-1.49').floor(scale: 1)).equals(dec('-1.5'));
});
test('with negative scale', () {
expectThat(dec('1').floor(scale: -1)).equals(dec('0'));
expectThat(dec('-1').floor(scale: -1)).equals(dec('-10'));
expectThat(dec('14.9').floor(scale: -1)).equals(dec('10'));
expectThat(dec('-14.9').floor(scale: -1)).equals(dec('-20'));
});
});
group('ceil()', () {
test('without scale', () {
expectThat(dec('1').ceil()).equals(dec('1'));
expectThat(dec('-1').ceil()).equals(dec('-1'));
expectThat(dec('-1.49').ceil()).equals(dec('-1'));
expectThat(dec('1.49').ceil()).equals(dec('2'));
});
test('with positive scale', () {
expectThat(dec('1').ceil(scale: 1)).equals(dec('1'));
expectThat(dec('-1').ceil(scale: 1)).equals(dec('-1'));
expectThat(dec('-1.49').ceil(scale: 1)).equals(dec('-1.4'));
expectThat(dec('1.49').ceil(scale: 1)).equals(dec('1.5'));
});
test('with negative scale', () {
expectThat(dec('1').ceil(scale: -1)).equals(dec('10'));
expectThat(dec('-1').ceil(scale: -1)).equals(dec('0'));
expectThat(dec('-14.9').ceil(scale: -1)).equals(dec('-10'));
expectThat(dec('14.9').ceil(scale: -1)).equals(dec('20'));
});
});
group('round()', () {
test('without scale', () {
expectThat(dec('1.4999').round()).equals(dec('1'));
expectThat(dec('2.5').round()).equals(dec('3'));
expectThat(dec('-2.51').round()).equals(dec('-3'));
expectThat(dec('-2').round()).equals(dec('-2'));
});
test('with positive scale', () {
expectThat(dec('1.4999').round(scale: 1)).equals(dec('1.5'));
expectThat(dec('2.5').round(scale: 1)).equals(dec('2.5'));
expectThat(dec('-2.51').round(scale: 1)).equals(dec('-2.5'));
expectThat(dec('-2').round(scale: 1)).equals(dec('-2'));
});
test('with negative scale', () {
expectThat(dec('1.4999').round(scale: -1)).equals(dec('0'));
expectThat(dec('12.5').round(scale: -1)).equals(dec('10'));
expectThat(dec('-25.1').round(scale: -1)).equals(dec('-30'));
expectThat(dec('-24').round(scale: -1)).equals(dec('-20'));
});
});
group('truncate()', () {
test('without scale', () {
expectThat(dec('1.4999').truncate()).equals(dec('1'));
expectThat(dec('2.5').truncate()).equals(dec('2'));
expectThat(dec('-2.51').truncate()).equals(dec('-2'));
expectThat(dec('-2').truncate()).equals(dec('-2'));
});
test('with positive scale', () {
expectThat(dec('1.4999').truncate(scale: 1)).equals(dec('1.4'));
expectThat(dec('2.5').truncate(scale: 1)).equals(dec('2.5'));
expectThat(dec('-2.51').truncate(scale: 1)).equals(dec('-2.5'));
expectThat(dec('-2').truncate(scale: 1)).equals(dec('-2'));
});
test('with negative scale', () {
expectThat(dec('1.4999').truncate(scale: -1)).equals(dec('0'));
expectThat(dec('12.5').truncate(scale: -1)).equals(dec('10'));
expectThat(dec('-25.1').truncate(scale: -1)).equals(dec('-20'));
expectThat(dec('-24').truncate(scale: -1)).equals(dec('-20'));
});
});
test('shift()', () {
expectThat(dec('123.4567').shift(0)).equals(dec('123.4567'));
expectThat(dec('123.4567').shift(1)).equals(dec('1234.567'));
expectThat(dec('123.4567').shift(2)).equals(dec('12345.67'));
expectThat(dec('123.4567').shift(6)).equals(dec('123456700'));
expectThat(dec('123.4567').shift(-1)).equals(dec('12.34567'));
expectThat(dec('123.4567').shift(-2)).equals(dec('1.234567'));
expectThat(dec('123.4567').shift(-3)).equals(dec('0.1234567'));
});
test('clamp(Decimal lowerLimit, Decimal upperLimit)', () {
expectThat(dec('2.51').clamp(dec('1'), dec('3'))).equals(dec('2.51'));
expectThat(dec('2.51').clamp(dec('2.6'), dec('3'))).equals(dec('2.6'));
expectThat(dec('2.51').clamp(dec('1'), dec('2.5'))).equals(dec('2.5'));
});
test('toBigInt()', () {
expectThat(dec('2.51').toBigInt()).equals(BigInt.from(2));
expectThat(dec('-2.51').toBigInt()).equals(BigInt.from(-2));
expectThat(dec('-2').toBigInt()).equals(BigInt.from(-2));
});
test('toDouble()', () {
expectThat(dec('2.51').toDouble()).equals(2.51);
expectThat(dec('-2.51').toDouble()).equals(-2.51);
expectThat(dec('-2').toDouble()).equals(-2.0);
});
test('precision', () {
expectThat(dec('100').precision).equals(3);
expectThat(dec('10000').precision).equals(5);
expectThat(dec('-10000').precision).equals(5);
expectThat(dec('1e5').precision).equals(6);
expectThat(dec('100.000').precision).equals(3);
expectThat(dec('100.1').precision).equals(4);
expectThat(dec('100.0000001').precision).equals(10);
expectThat(dec('-100.0000001').precision).equals(10);
expectThat(dec('100.000000000000000000000000000001').precision).equals(33);
expectThat(dec('0').precision).equals(1);
expectThat(dec('0.10').precision).equals(2);
expectThat(dec('0.00').precision).equals(1);
expectThat(dec('0.1').precision).equals(2);
expectThat(dec('0.01').precision).equals(3);
expectThat(dec('-0.01').precision).equals(3);
});
test('scale', () {
expectThat(dec('100').scale).equals(0);
expectThat(dec('10000').scale).equals(0);
expectThat(dec('100.000').scale).equals(0);
expectThat(dec('100.1').scale).equals(1);
expectThat(dec('100.0000001').scale).equals(7);
expectThat(dec('-100.0000001').scale).equals(7);
expectThat(dec('100.000000000000000000000000000001').scale).equals(30);
});
test('toStringAsFixed(int fractionDigits)', () {
for (final n in [0, 1, 23, 2.2, 2.499999, 2.5, 2.7, 1.235]) {
for (final p in [0, 1, 5, 10]) {
expectThat(dec(n.toString()).toStringAsFixed(p))
.equals(n.toStringAsFixed(p));
}
}
expectThat(dec('19').toStringAsFixed(5)).equals('19.00000');
});
test('toStringAsExponential(int fractionDigits)', () {
expectThat(dec('0').toStringAsExponential(0)).equals('0e+0');
for (final n in [0, 1, 23, 2.2, 2.499999, 2.5, 2.7, 1.235, -1.2, -0.02]) {
for (final p in [1, 5, 10]) {
expectThat(dec(n.toString()).toStringAsExponential(p))
.equals(n.toStringAsExponential(p));
}
}
// issue https://github.com/a14n/dart-decimal/issues/48
expectThat(dec('1.7976931348623157e+310').toStringAsExponential(10))
.equals('1.7976931349e+310');
// issue https://github.com/a14n/dart-decimal/issues/74
expectThat(dec('9.9999e+7').toStringAsExponential(2)).equals('1.00e+8');
});
test('toStringAsPrecision(int precision)', () {
expectThat(dec('0').toStringAsPrecision(1)).equals('0');
expectThat(dec('0').toStringAsPrecision(5)).equals('0.0000');
expectThat(dec('0').toStringAsPrecision(10)).equals('0.000000000');
expectThat(dec('1').toStringAsPrecision(1)).equals('1');
expectThat(dec('1').toStringAsPrecision(5)).equals('1.0000');
expectThat(dec('1').toStringAsPrecision(10)).equals('1.000000000');
expectThat(dec('23').toStringAsPrecision(1)).equals('20');
expectThat(dec('23').toStringAsPrecision(5)).equals('23.000');
expectThat(dec('23').toStringAsPrecision(10)).equals('23.00000000');
expectThat(dec('2.2').toStringAsPrecision(1)).equals('2');
expectThat(dec('2.2').toStringAsPrecision(5)).equals('2.2000');
expectThat(dec('2.2').toStringAsPrecision(10)).equals('2.200000000');
expectThat(dec('2.499999').toStringAsPrecision(1)).equals('2');
expectThat(dec('2.499999').toStringAsPrecision(5)).equals('2.5000');
expectThat(dec('2.499999').toStringAsPrecision(10)).equals('2.499999000');
expectThat(dec('2.5').toStringAsPrecision(1)).equals('3');
expectThat(dec('2.5').toStringAsPrecision(5)).equals('2.5000');
expectThat(dec('2.5').toStringAsPrecision(10)).equals('2.500000000');
expectThat(dec('2.7').toStringAsPrecision(1)).equals('3');
expectThat(dec('2.7').toStringAsPrecision(5)).equals('2.7000');
expectThat(dec('2.7').toStringAsPrecision(10)).equals('2.700000000');
expectThat(dec('1.235').toStringAsPrecision(1)).equals('1');
expectThat(dec('1.235').toStringAsPrecision(5)).equals('1.2350');
expectThat(dec('1.235').toStringAsPrecision(10)).equals('1.235000000');
});
test('issue #13', () {
expectThat(Decimal.parse('21.962962546543768').toString())
.equals('21.962962546543768');
});
test('zero', () {
expectThat(Decimal.zero).equals(Decimal.fromInt(0));
});
test('one', () {
expectThat(Decimal.one).equals(Decimal.fromInt(1));
});
test('ten', () {
expectThat(Decimal.ten).equals(Decimal.fromInt(10));
});
test('pow', () {
expectThat(dec('100').pow(0)).equals(dec('1').toRational());
expectThat(dec('100').pow(1)).equals(dec('100').toRational());
expectThat(dec('100').pow(2)).equals(dec('10000').toRational());
expectThat(dec('100').pow(-1)).equals(dec('0.01').toRational());
expectThat(dec('100').pow(-2)).equals(dec('0.0001').toRational());
expectThat(dec('0.1').pow(0)).equals(dec('1').toRational());
expectThat(dec('0.1').pow(1)).equals(dec('0.1').toRational());
expectThat(dec('0.1').pow(2)).equals(dec('0.01').toRational());
expectThat(dec('0.1').pow(-1)).equals(dec('10').toRational());
expectThat(dec('0.1').pow(-2)).equals(dec('100').toRational());
expectThat(dec('-1').pow(0)).equals(dec('1').toRational());
expectThat(dec('-1').pow(1)).equals(dec('-1').toRational());
expectThat(dec('-1').pow(2)).equals(dec('1').toRational());
expectThat(dec('-1').pow(-1)).equals(dec('-1').toRational());
expectThat(dec('-1').pow(-2)).equals(dec('1').toRational());
});
test('fromJson', () async {
expectThat(Decimal.fromJson('1')).equals(Decimal.one);
await expectThat(() => Decimal.fromJson('-1')).returnsNormally();
await expectThat(() => Decimal.fromJson('1.')).returnsNormally();
await expectThat(() => Decimal.fromJson('1.0')).returnsNormally();
});
test('toJson', () {
const encoder = JsonEncoder();
expectThat(encoder.convert({
'zero': Decimal.zero,
'one': Decimal.one,
})).equals(
'{'
'"zero":"${Decimal.zero}",'
'"one":"${Decimal.one}"'
'}',
);
});
test('Rational.hasFinitePrecision', () {
const p = Rational.parse;
for (final r in [
p('100'),
p('100.100'),
p('1') / p('5'),
(p('1') / p('3')) * p('3'),
p('0.00000000000000000000001'),
]) {
expectThat(r.hasFinitePrecision).isTrue;
}
for (final r in [p('1') / p('3')]) {
expectThat(r.hasFinitePrecision).isFalse;
}
});
test('Rational.toDecimal', () {
Rational r(int numerator, int denominator) =>
Rational.fromInt(numerator, denominator);
expectThat(r(1, 1).toDecimal()).equals(dec('1'));
expectThat(() => r(1, 3).toDecimal()).throwsA<AssertionError>();
expectThat(r(1, 3).toDecimal(scaleOnInfinitePrecision: 1))
.equals(dec('0.3'));
expectThat(r(1, 4).toDecimal(scaleOnInfinitePrecision: 1))
.equals(dec('0.25'));
expectThat(r(2, 3).toDecimal(
scaleOnInfinitePrecision: 1,
toBigInt: (v) => v.round(),
)).equals(dec('0.7'));
});
}
================================================
FILE: test/intl_test.dart
================================================
// Copyright 2013 Alexandre Ardhuin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'dart:math';
import 'package:decimal/decimal.dart';
import 'package:decimal/intl.dart';
import 'package:expector/expector.dart';
import 'package:intl/intl.dart';
import 'package:test/test.dart' show group, test;
Decimal dec(String value) => Decimal.parse(value);
void main() {
group('DecimalFormatter.format', () {
test('outputs the same result as with double', () {
final formats = <NumberFormat>[
NumberFormat.decimalPattern('en-US'),
NumberFormat.decimalPattern('fr-FR'),
];
final numbers = <String>[
'0',
'1',
'-1.123',
'123456789.0123',
];
for (var format in formats) {
final formatter = DecimalFormatter(format);
for (var number in numbers) {
expectThat(formatter.format(dec(number)))
.equals(format.format(double.parse(number)));
}
}
});
test('outputs result for long decimal', () {
final format = NumberFormat.decimalPattern('en-US');
final formatter = DecimalFormatter(format);
expectThat(formatter.format(dec(
'12345678901234567890123456789012345678901234567890.1234567890123456789012345678901234567890123456789')))
.equals(
'12,345,678,901,234,567,890,123,456,789,012,345,678,901,234,567,890.123');
});
test('outputs the same result as origin', () {
// intl doesn't work with maximumFractionDigits > 15 on web and > 18 otherwise
const maxPreciseWebInt = 0x20000000000000;
final maxFractionalDigitsForIntl = log(maxPreciseWebInt) ~/ log(10);
final format = NumberFormat()
..turnOffGrouping()
..maximumFractionDigits = maxFractionalDigitsForIntl;
final formatter = DecimalFormatter(format);
final numbers = <String>[
'0',
'1',
'-1.123',
'123456789.0123',
];
for (var number in numbers) {
expectThat(formatter.format(dec(number))).equals(number);
}
expectThat(formatter.format(dec(
'12345678901234567890123456789012345678901234567890.1234567890123456789012345678901234567890123456789')))
.equals(
'12345678901234567890123456789012345678901234567890.123456789012346');
});
test('with compactCurrency outputs the correct results', () {
final format = NumberFormat.compactCurrency(locale: 'en-US', symbol: '');
final formatter = DecimalFormatter(format);
expectThat(formatter.format(dec('1000000000'))).equals('1B');
});
test('with currencyFormatter', () {
final currencyFormatter = DecimalFormatter(NumberFormat.compact());
expectThat(currencyFormatter.format(dec('1000'))).equals('1K');
expectThat(currencyFormatter.format(dec('1000.1'))).equals('1K');
expectThat(currencyFormatter.format(dec('1234567890.1234')))
.equals('1.23B');
});
});
group('DecimalFormatter.parse', () {
test('handle invalid Decimal', () {
final plainFormatter = DecimalFormatter(NumberFormat());
expectThat(() => plainFormatter.parse('NaN')).throwsA<FormatException>();
expectThat(plainFormatter.tryParse('NaN')).isNull;
expectThat(() => plainFormatter.parse('a')).throwsA<FormatException>();
expectThat(plainFormatter.tryParse('a')).isNull;
expectThat(() => plainFormatter.parse('+Infinity'))
.throwsA<FormatException>();
expectThat(plainFormatter.tryParse('+Infinity')).isNull;
});
test('can parse plain decimal', () {
final plainFormatter = DecimalFormatter(NumberFormat());
expectThat(plainFormatter.parse('3.14')).equals(dec('3.14'));
expectThat(plainFormatter.parse('03.14')).equals(dec('3.14'));
expectThat(plainFormatter.parse('-3.14')).equals(-dec('3.14'));
expectThat(plainFormatter.tryParse('3.14')).equals(dec('3.14'));
expectThat(plainFormatter.tryParse('03.14')).equals(dec('3.14'));
expectThat(plainFormatter.tryParse('-3.14')).equals(-dec('3.14'));
expectThat(plainFormatter.tryParse('qsfd')).isNull;
});
test('can parse currency decimal', () {
final currencyFormatter =
DecimalFormatter(NumberFormat.simpleCurrency(name: 'USD'));
expectThat(currencyFormatter.parse(r'$3.14')).equals(dec('3.14'));
expectThat(currencyFormatter.parse(r'$03.14')).equals(dec('3.14'));
expectThat(currencyFormatter.parse(r'-$3.14')).equals(-dec('3.14'));
expectThat(currencyFormatter.tryParse(r'$3.14')).equals(dec('3.14'));
expectThat(currencyFormatter.tryParse(r'$03.14')).equals(dec('3.14'));
expectThat(currencyFormatter.tryParse(r'-$3.14')).equals(-dec('3.14'));
expectThat(currencyFormatter.tryParse('qsfd')).isNull;
});
});
}
gitextract_94seb90j/
├── .github/
│ ├── dependabot.yml
│ └── workflows/
│ └── dart.yml
├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── NOTICE
├── README.md
├── analysis_options.yaml
├── example/
│ ├── lib/
│ │ └── example.dart
│ └── pubspec.yaml
├── lib/
│ ├── decimal.dart
│ └── intl.dart
├── pubspec.yaml
└── test/
├── decimal_test.dart
└── intl_test.dart
SYMBOL INDEX (49 symbols across 5 files)
FILE: example/lib/example.dart
function main (line 3) | void main()
FILE: lib/decimal.dart
class Decimal (line 28) | class Decimal implements Comparable<Decimal> {
method parse (line 50) | Decimal parse(String source)
method tryParse (line 66) | Decimal? tryParse(String source)
method toRational (line 84) | Rational toRational()
method toString (line 100) | String toString()
method toJson (line 116) | String toJson()
method compareTo (line 119) | int compareTo(Decimal other)
method remainder (line 160) | Decimal remainder(Decimal other)
method abs (line 178) | Decimal abs()
method floor (line 200) | Decimal floor({int scale = 0})
method ceil (line 214) | Decimal ceil({int scale = 0})
method round (line 231) | Decimal round({int scale = 0})
method _scaleAndApply (line 233) | Decimal _scaleAndApply(int scale, BigInt Function(Rational) f)
method truncate (line 239) | Decimal truncate({int scale = 0})
method shift (line 250) | Decimal shift(int value)
method clamp (line 253) | Decimal clamp(Decimal lowerLimit, Decimal upperLimit)
method toBigInt (line 260) | BigInt toBigInt()
method toDouble (line 271) | double toDouble()
method toStringAsFixed (line 304) | String toStringAsFixed(int fractionDigits)
method toStringAsExponential (line 316) | String toStringAsExponential([int fractionDigits = 0])
method toStringAsPrecision (line 348) | String toStringAsPrecision(int precision)
method pow (line 379) | Rational pow(int exponent)
method _unifyScale (line 381) | (Decimal, Decimal) _unifyScale(Decimal d1, Decimal d2)
function toDecimal (line 416) | Decimal toDecimal({
function toDecimal (line 471) | Decimal toDecimal()
function toDecimal (line 477) | Decimal toDecimal()
FILE: lib/intl.dart
class DecimalFormatter (line 19) | class DecimalFormatter {
method parse (line 25) | Decimal parse(String text)
method tryParse (line 29) | Decimal? tryParse(String text)
method format (line 38) | String format(Decimal number)
class _DecimalIntl (line 41) | class _DecimalIntl {
method abs (line 65) | _DecimalIntl abs()
method remainder (line 92) | _DecimalIntl remainder(dynamic other)
method toInt (line 95) | int toInt()
method toDouble (line 97) | double toDouble()
method round (line 99) | _DecimalIntl round()
method toString (line 109) | String toString()
class _DartDecimalNumberParser (line 112) | class _DartDecimalNumberParser extends NumberParserBase<Decimal> {
method fromNormalized (line 116) | Decimal fromNormalized(String normalizedText)
method nan (line 120) | Decimal nan()
method negativeInfinity (line 123) | Decimal negativeInfinity()
method positiveInfinity (line 127) | Decimal positiveInfinity()
method scaled (line 131) | Decimal scaled(Decimal parsed, int scale)
FILE: test/decimal_test.dart
function dec (line 22) | Decimal dec(String value)
function main (line 24) | void main()
function r (line 438) | Rational r(int numerator, int denominator)
FILE: test/intl_test.dart
function dec (line 23) | Decimal dec(String value)
function main (line 25) | void main()
Condensed preview — 15 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (69K chars).
[
{
"path": ".github/dependabot.yml",
"chars": 373,
"preview": "# Set update schedule for GitHub Actions\n# See https://docs.github.com/en/code-security/supply-chain-security/keeping-yo"
},
{
"path": ".github/workflows/dart.yml",
"chars": 838,
"preview": "# This workflow uses actions that are not certified by GitHub.\n# They are provided by a third-party and are governed by\n"
},
{
"path": ".gitignore",
"chars": 56,
"preview": "packages\n.packages\npubspec.lock\n.pub/\n.dart_tool\nbuild/\n"
},
{
"path": "CHANGELOG.md",
"chars": 5280,
"preview": "# 3.2.4 (2025-06-22)\n\n- Fix issue with scale of zero causing problem in addition/substraction with zero.\n\n# 3.2.3 (2025-"
},
{
"path": "LICENSE",
"chars": 11357,
"preview": "\n Apache License\n Version 2.0, January 2004\n "
},
{
"path": "NOTICE",
"chars": 557,
"preview": "Copyright 2013 Alexandre Ardhuin\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this f"
},
{
"path": "README.md",
"chars": 2102,
"preview": "# Dart Decimals\n\n[](https://gi"
},
{
"path": "analysis_options.yaml",
"chars": 183,
"preview": "include: package:lints/recommended.yaml\nanalyzer:\n language:\n strict-casts: true\n strict-inference: true\n stri"
},
{
"path": "example/lib/example.dart",
"chars": 110,
"preview": "import 'package:decimal/decimal.dart';\n\nvoid main() {\n print(Decimal.parse('0.1') + Decimal.parse('0.2'));\n}\n"
},
{
"path": "example/pubspec.yaml",
"chars": 229,
"preview": "name: decimal_example\nversion: 0.0.1\ndescription: Example app for the decimal package.\nhomepage: https://github.com/a14n"
},
{
"path": "lib/decimal.dart",
"chars": 15077,
"preview": "// Copyright 2013 Alexandre Ardhuin\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not"
},
{
"path": "lib/intl.dart",
"chars": 4265,
"preview": "// Copyright 2013 Alexandre Ardhuin\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not"
},
{
"path": "pubspec.yaml",
"chars": 350,
"preview": "name: decimal\nversion: 3.2.4\ndescription: >\n The decimal package allows you to deal with decimal numbers without losing"
},
{
"path": "test/decimal_test.dart",
"chars": 20106,
"preview": "// Copyright 2013 Alexandre Ardhuin\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not"
},
{
"path": "test/intl_test.dart",
"chars": 5345,
"preview": "// Copyright 2013 Alexandre Ardhuin\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not"
}
]
About this extraction
This page contains the full source code of the a14n/dart-decimal GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 15 files (64.7 KB), approximately 18.3k tokens, and a symbol index with 49 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.