0

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

dosytres
  • 2,096
  • 3
  • 10
  • 21

3 Answers3

3
String removeZero(double money) {
  var response = money.toString();

  if (money.toString().split(".").length > 0) {
    var decmialPoint = money.toString().split(".")[1];
    if (decmialPoint == "0") {
      response = response.split(".0").join("");
    }
    if (decmialPoint == "00") {
      response = response.split(".00").join("");
    }
  }

  return response;
}

Edit: I added to check if the string contains a decimal point or not to avoid index out of bounds issue

  • you can also do price.value.toString().replaceAll(".00", "") – Tewedaj Getahun Jan 28 '23 at 09:17
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 30 '23 at 20:54
-1

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

Code Master
  • 437
  • 1
  • 7
-3

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);
}