Fixed 包允许您存储和执行数字上的数学运算
使用固定比例(固定小数位数)。

所有金额都存储为整数,以便进行精确的数学运算。

Fixed 包允许您明确控制存储的小数位数(比例)。

Fixed 实例是不可变的。

在进行数学运算后,您可能需要使用所需的比例构建一个新的 Fixed 对象。

对于乘法,结果的比例是两个比例的总和。
例如

  0.01 * 0.02 = 0.0002

final rate = Fixed.fromMinorUnits(75486, scale: 5); // == 0.75486
final auDollars = Fixed.fromMinorUnits(100, scale: 2); // == 1.00
final usDollarsHighScale = auDollars * rate;  // ==0.7548600, scale = 7

/// reduce the scale to 2 decimal places.
final usDollars = Fixed(usDollarsHighScale, scale: 2); // == 0.75

进行除法时,结果的比例将是
两个操作数中较大的比例。

final winnings = Fixed.fromMinorUnits(600000, scale: 5); // == 6.00000
final winners = Fixed.fromMinorUnits(200, scale: 2); // == 2.00
final share = winnings / winners;  // == 3.00000, scale = 5

构造函数

创建 Fixed 对象有多种方法。

final t2 = Fixed.fromMinorUnits(1234, scale: 3); // == 1.234
final t3 = Fixed.fromBigInt(BigInt.from(1234), scale: 3)); // == 1.234
final t4 = Fixed(t1); // == 1.234
final t5 = Fixed.parse('1.234', scale: 3); // == 1.234

// This is the least desireable method as it can introduce
// rounding errors.
final t6 = Fixed.from(1.234, scale: 3); // == 1.234

运算符

Fixed 提供数学运算。

final t1 = Fixed.parse('1.23'); // = 1.23
final t2 = Fixed.fromMinorUnits(100, scale: 2); // = 1.00

final t3 = t1 + t2; // == 2.23
final t4 = t2 - t1; // == 0.23
final t5 = t1 * t2; // == 1.23;
final t6 = t1 / t2; // == 1.23
final t7 = -t1; // == -1.23

比较

final t1 = Fixed.from(1.23);
final t2 = Fixed.fromMinorUnits(123, scale: 2);
final t3 = Fixed.fromBigInt(BigInt.from(1234), scale: 3));

expect(t1 == t2, isTrue);
expect(t1 < t3, isTrue);
expect(t1 <= t3, isTrue);
expect(t1 > t3, isFalse);
expect(t1 >= t3, isFalse);
expect(t1 != t3, isTrue);
expect(-t1, equals(Fixed.fromMinorUnits(-123, scale: 2)));

expect(t1.isPositive, isTrue);
expect(t1.isNegative, isFalse);
expect(t1.isZero, isTrue);

expect(t1.compareTo(t2) , isTrue);

解析

您可以从字符串解析数字。

var t1 = Fixed.parse('1.234', pattern: '#.#', scale: 2);
expect(t1.minorUnits.toInt(), equals(1234));
expect(t1.scale, equals(2));


var t1 = Fixed.parse('1,000,000.234', pattern: '#,###.#', scale: 2);
expect(t1.minorUnits.toInt(), equals(1000000.23));
expect(t1.scale, equals(2));


/// for countries that use . for thousand separators
var t1 = Fixed.parse('1.000.000,234', pattern: '#.###,#', scale: 2, invertSeparators);
expect(t1.minorUnits.toInt(), equals(1000000.23));
expect(t1.scale, equals(2));

格式化

您也可以将数字格式化为字符串。

var t1 = Fixed.fromMinorUnits(1234, scale: 3);

expect(t3.toString(), equals('1.234'));

expect(t3.format('00.###0'), equals('00.12340'));

expect(t3.format('00.###0', invertSeparators: true), equals('00,12340'));

GitHub

查看 Github