如何使用Dart删除尾随零
我想要使用Dart删除尾随零的最佳解决方案。如果我有一个12.0的double,它应该输出12。如果我有一个双精度的12.5,它应该输出12.5如何使用Dart删除尾随零,dart,flutter,Dart,Flutter,我想要使用Dart删除尾随零的最佳解决方案。如果我有一个12.0的double,它应该输出12。如果我有一个双精度的12.5,它应该输出12.5 void main() { double x1 = 12.0; double x2 = 12.5; String s1 = x1.toString().trim(); String s2 = x2.toString().trim(); print('s1 is $s1 and s2 is $s2'); } 尝试修剪方法更新 更
void main() {
double x1 = 12.0;
double x2 = 12.5;
String s1 = x1.toString().trim();
String s2 = x2.toString().trim();
print('s1 is $s1 and s2 is $s2');
}
尝试修剪方法更新更好的方法是使用以下方法:
String removeDecimalZeroFormat(double n) {
return n.toStringAsFixed(n.truncateToDouble() == n ? 0 : 1);
}
num doubleWithoutDecimalToInt(double val) {
return val % 1 == 0 ? val.toInt() : val;
}
旧的这符合以下要求: 双x=12.0
双y=12.5 打印(x.toString().replaceAll(RegExp(r'.0'),'')
打印(y.toString().replaceAll(RegExp(r'.0'),'') X输出:12
Y输出:12.5我为该功能创建了正则表达式模式
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)"), "");
我想出了@John的改进版本
static String getDisplayPrice(double price) {
price = price.abs();
final str = price.toStringAsFixed(price.truncateToDouble() == price ? 0 : 2);
if (str == '0') return '0';
if (str.endsWith('.0')) return str.substring(0, str.length - 2);
if (str.endsWith('0')) return str.substring(0, str.length -1);
return str;
}
// 10 -> 10
// 10.0 -> 10
// 10.50 -> 10.5
// 10.05 -> 10.05
// 10.000000000005 -> 10
使用数字格式:
String formatQuantity(double v) {
if (v == null) return '';
NumberFormat formatter = NumberFormat();
formatter.minimumFractionDigits = 0;
formatter.maximumFractionDigits = 2;
return formatter.format(v);
}
如果要将不带小数的double转换为int,但如果有小数,则将其保留为double,我使用以下方法:
String removeDecimalZeroFormat(double n) {
return n.toStringAsFixed(n.truncateToDouble() == n ? 0 : 1);
}
num doubleWithoutDecimalToInt(double val) {
return val % 1 == 0 ? val.toInt() : val;
}
=======下面的测试用例=======
000 -> 000
1230 -> 1230
123.00 -> 123
123.001 -> 123.001
123.00100 -> 123.001
abc000 -> abc000
abc000.0000 -> abc000
abc000.001 -> abc000.001
这里有一个非常简单的方法。使用if-else,我将检查数字是否等于其整数或分数,并采取相应的措施
num x = 24/2; // returns 12.0
num y = 25/2; // returns 12.5
if (x == x.truncate()) {
// it is true in this case so i will do something like
x = x.toInt();
}
我找到了另一个解决方案,使用
num
而不是double
。在我的例子中,我正在将字符串解析为num:
void main() {
print(num.parse('50.05').toString()); //prints 50.05
print(num.parse('50.0').toString()); //prints 50
}
为了改进@John的答案:这里有一个简短的版本
String formatNumber(double n) {
return n.toStringAsFixed(0) //removes all trailing numbers after the decimal.
}
的带有省道扩展名的版本:
extension StringRegEx on String {
String removeTrailingZero() {
if (!this.contains('.')) {
return this;
}
String trimmed = this.replaceAll(RegExp(r'0*$'), '');
if (!trimmed.endsWith('.')) {
return trimmed;
}
return trimmed.substring(0, this.length - 1);
}
}
以下是我的想法:
extension DoubleExtensions on double {
String toStringWithoutTrailingZeros() {
if (this == null) return null;
return truncateToDouble() == this ? toInt().toString() : toString();
}
}
void main() {
group('DoubleExtensions', () {
test("toStringWithoutTrailingZeros's result matches the expected value for a given double",
() async {
// Arrange
final _initialAndExpectedValueMap = <double, String>{
0: '0',
35: '35',
-45: '-45',
100.0: '100',
0.19: '0.19',
18.8: '18.8',
0.20: '0.2',
123.32432400: '123.324324',
-23.400: '-23.4',
null: null
};
_initialAndExpectedValueMap.forEach((key, value) {
final initialValue = key;
final expectedValue = value;
// Act
final actualValue = initialValue.toStringWithoutTrailingZeros();
// Assert
expect(actualValue, expectedValue);
});
});
});
}
extension-double{
字符串到字符串,不带trailingzero(){
if(this==null)返回null;
返回truncateToDouble()==this?toInt().toString():toString();
}
}
void main(){
组('DoubleExtensions',(){
test(“toStringWithoutTrailingZeros的结果与给定double的预期值匹配”,
()异步{
//安排
最终_initialAndExpectedValueMap={
0: '0',
35: '35',
-45: '-45',
100.0: '100',
0.19: '0.19',
18.8: '18.8',
0.20: '0.2',
123.32432400: '123.324324',
-23.400: '-23.4',
空:空
};
_initialAndExpectedValueMap.forEach((键,值){
最终初始值=键;
最终期望值=值;
//表演
最终实际值=initialValue.ToString不带跟踪零();
//断言
expect(实际值、期望值);
});
});
});
}
}
许多答案对小数点很多的数字不适用,而是以货币价值为中心 要删除所有尾随零,而不考虑长度,请执行以下操作:
removeTrailingZeros(String n) {
return n.replaceAll(RegExp(r"([.]*0+)(?!.*\d)"), "");
}
输入: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
);
}
}
这适用于所有场景。toStringAsFixed(n.truncateToDouble()方法在我的答案中,当基于小数位的值小于1(即0.95)时,会自动将其舍入为1,这是一个不必要的副作用。为什么不使用您声明和分配的正则表达式?这是以下部分:
RegExp regex=RegExp(r)([.]*0)(!*\d)”;
相反,您在replaceAll
中指定了一个新的RegExp;返回值为12.50;RegExp(r'\.0')对于me@alexwan02使用RegExp(r“([.]*0+(...*\d)”)
删除小数点后的所有尾随零。这是不正确的。当您超过100时,您将得到10。最后一行应返回trimmed.substring(0,trimmed.length-1);
如果变量x/y不在双精度范围内,则不起作用。答案很好,即使有多个尾随零,也能起作用。谢谢。
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
);
}
}