问题描述
我只需要在小数点后取两个数字,我必须处理的 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)}';
}