搜索插件、代码仓与 APP 分类

插件详情v3.2.6

decimal

decimal 包允许您处理十进制数字而不会丢失精度。

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
105万
喜欢数
433
Pub 分数
160

安装插件

flutter pub add decimal

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

decimal 包在 Dart 中提供了精确的十进制算术,能够准确处理十进制数字,避免浮点运算中常见的精度损失。它支持精确的十进制表示和算术运算,非常适合用于财务计算以及其他需要高精度的场景。该包可在所有主要平台上兼容,包括移动设备、网页和桌面端。它提供了一个简洁的 API,用于创建、操作和格式化十进制数值,并完全控制舍入模式和精度。

适合场景

  • 财务计算
  • 科学计算
  • 货币处理
  • 精确的数据处理
  • 单位转换

主要特点

  • 高精度十进制算术
  • 无浮点精度损失
  • 对舍入模式的支持
  • 跨平台兼容性
  • 易于使用的 API

适合对象

  • 需要精确十进制数学运算的应用程序
  • 财务或会计软件
  • 对精度要求严格的情况
  • 开发人员避免浮点精度问题

使用建议

  • 比双精度浮点数略高的内存使用量
  • 未针对性能密集型数值工作负载进行优化
  • 需要显式使用,而不是原生数值类型

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

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').

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

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));
}

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));
}

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

License

Apache 2.0

所属分类

依赖

依赖清单 2 项

源码仓库

使用此插件的项目

所在榜单