moneyFormatWithUnit method

String moneyFormatWithUnit(
  1. bool autoMoneyUnit
)

带单位格式化(输入单位为分)。

autoMoneyUnit 为 true 且金额 >= 10000 元(即 >= 1000000 分)时, 自动折算为「万」单位输出;否则除以 100 输出两位小数元。

走 Decimal 运算(与 StringExt.moneyFormatWithUnit 同策略),避免 大额输入时 double 精度丢失;Decimal 无法解析的异形值(如科学计数法 极大 double)回退旧 double 路径保持行为不变。

Implementation

String moneyFormatWithUnit(bool autoMoneyUnit) {
  final value = this;
  if (value == null) return '0.00';

  final dec = Decimal.tryParse(value.toString());
  if (dec != null) {
    if (autoMoneyUnit && dec >= Decimal.fromInt(1000000)) {
      return '${dec.shift(-6).toStringAsFixed(2)}万';
    }
    return dec.shift(-2).toStringAsFixed(2);
  }

  // 回退:异形值走旧 double 路径。
  if (autoMoneyUnit && value >= 1000000) {
    return '${(value / 1000000).toStringAsFixed(2)}万';
  }
  return (value / 100).toStringAsFixed(2);
}