我想要使用 Dart 去除尾随零的最佳解决方案。如果我有一个 12.0 的双精度它应该输出 12。如果我有一个 12.5 的双精度它应该输出 12.5
小智 27
我为该功能制作了正则表达式模式。
double num = 12.50; //12.5
double num2 = 12.0; //12
double num3 = 1000; //1000
RegExp regex = RegExp(r"([.]*0)(?!.*\d)");
String s = num.toString().replaceAll(RegExp(r"([.]*0)(?!.*\d)"), "");
Run Code Online (Sandbox Code Playgroud)
Joh*_*ohn 18
更新
一个更好的方法,只需使用此方法:
String removeDecimalZeroFormat(double n) {
return n.toStringAsFixed(n.truncateToDouble() == n ? 0 : 1);
}
Run Code Online (Sandbox Code Playgroud)
OLD
这符合要求:
双 x = 12.0;
双 y = 12.5;
打印(x.toString().replaceAll(RegExp(r'.0'), ''));
打印(y.toString().replaceAll(RegExp(r'.0'), ''));
X 输出:12
Y 输出:12.5
Aug*_*imo 15
许多答案不适用于具有多个小数点的数字,并且以货币价值为中心。
无论长度如何,删除所有尾随零:
removeTrailingZeros(String n) {
return n.replaceAll(RegExp(r"([.]*0+)(?!.*\d)"), "");
}
Run Code Online (Sandbox Code Playgroud)
输入:12.00100003000
输出:12.00100003
如果您只想删除小数点后的尾随 0,请使用以下命令:
removeTrailingZerosAndNumberfy(String n) {
if(n.contains('.')){
return double.parse(
n.replaceAll(RegExp(r"([.]*0+)(?!.*\d)"), "") //remove all trailing 0's and extra decimals at end if any
);
}
else{
return double.parse(
n
);
}
}
Run Code Online (Sandbox Code Playgroud)
gre*_*sse 11
使用数字格式:
String formatQuantity(double v) {
if (v == null) return '';
NumberFormat formatter = NumberFormat();
formatter.minimumFractionDigits = 0;
formatter.maximumFractionDigits = 2;
return formatter.format(v);
}
Run Code Online (Sandbox Code Playgroud)
Sim*_*onC 10
如果您想要将不带小数的 double 转换为 int 但如果有小数则将其保留为 double,我使用此方法:
num doubleWithoutDecimalToInt(double val) {
return val % 1 == 0 ? val.toInt() : val;
}
Run Code Online (Sandbox Code Playgroud)
我找到了另一种解决方案,使用num而不是double. 就我而言,我将 String 解析为 num:
void main() {
print(num.parse('50.05').toString()); //prints 50.05
print(num.parse('50.0').toString()); //prints 50
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10507 次 |
| 最近记录: |