微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在小数点后取两个数字,颤振中数字为-7.922816251426434e+28

如何解决如何在小数点后取两个数字,颤振中数字为-7.922816251426434e+28

我只需要在小数点后取两个数字,我必须处理的 json 响应中出现奇怪的数字,例如 -7.922816251426434e+28

HoldedQuantity.toStringAsFixed(2);

我刚试过这个方法但没有用,我该如何处理Flutter dart中的这些数字,请帮忙

解决方法

double num1 = double.parse((12.3412).toStringAsFixed(2)); // 12.34

double num2 = double.parse((12.5668).toStringAsFixed(2)); // 12.57

double num3 = double.parse((-12.3412).toStringAsFixed(2)); // -12.34

double num4 = double.parse((-12.3456).toStringAsFixed(2));

1.toStringAsFixed(3);  // 1.000
(4321.12345678).toStringAsFixed(3);  // 4321.123
(4321.12345678).toStringAsFixed(5);  // 4321.12346
123456789012345678901.toStringAsFixed(3);  // 123456789012345683968.000
1000000000000000000000.toStringAsFixed(3); // 1e+21
5.25.toStringAsFixed(0); // 5
,

解决方法

void main() {
  var number = -7.922816251426434e+28;
  print(appToStringAsFixed(number,2)); // -7.92
}

String appToStringAsFixed(double number,int afterDecimal) {
  return '${number.toString().split('.')[0]}.${number.toString().split('.')[1].substring(0,afterDecimal)}';
}

或作为扩展

void main() {
  var number = -7.922816251426434e+28;
  print(number.expToStringAsFixed(2)); // -7.92
}

extension DecimalUtil on double {
  String expToStringAsFixed(int afterDecimal) => '${this.toString().split('.')[0]}.${this.toString().split('.')[1].substring(0,afterDecimal)}';
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。