I am currently trying to render the price value of products using a widget in Flutter. To do so, I pass the state and render it in the argument from the corresponding widget. What I need to achieve is to hide the 2 decimals of my Double type priceValue and show them if they are != to 0.
Like so, if state.priceValue = 12.00 $ => should show 12 if state.priceValue = 12.30 $ => should show 12.30
CodePudding user response:
Hello you could use an extension like that:
extension myExtension on double{
String get toStringV2{
final intPart = truncate();
if(this-intPart ==0){
return '$intPart';
}else{
return '$this';
}
}
}
To use the extension:
void main() {
double numberWithDecimals = 10.8;
double numberWithoutDecimals = 10.00;
//print
print(numberWithDecimals.toStringV2);
print(numberWithoutDecimals.toStringV2);
}
CodePudding user response:
Try this:
String price = "12.00$"
print(price.replaceAll(".00", ""));
Or refer to this: How to remove trailing zeros using Dart
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(regex, '');
But the second option will remove all trailing zeros so 12.30
will be 12.3
instead