Flutter, converting a low value double to currency

I want to convert a low value double like (0.0003009585) to show as a currency ($0.0003).

Intl package NumberFormat() will show it as $0 for different currency formats.

Tried different RegexExp did’nt work.

These code also doesnot work

String numToCurrency(double num) {
  final String numThreeZero = num.toStringAsFixed(2);

  final String numWithComma = NumberFormat.decimalPattern().format(double.parse(numThreeZero));



  if (numWithComma == '0') {
    final strNum = num.toString();

    String fixedNum = '';

    for (int i = 0; i < strNum.length; i++) {
      if (strNum[i] == '0' || strNum[i] == '.') continue;

      fixedNum = num.toStringAsFixed(i);
    }

    return fixedNum;
  } else {
    return numWithComma;
  }
}

>Solution :

Using loop to determine the number of decimal places to round off to. The loop increments the decimalPlaces variable until the product of value and 10 raised to the power of decimalPlaces is greater than or equal to 1. This effectively counts the number of decimal places needed to represent value.

double value = 0.00030234;

if (value > 0) {
  // Get the number of decimal places to round off to
  int decimalPlaces = 0;
  while (value * pow(10, decimalPlaces) < 1) {
    decimalPlaces++;
  }
  // Round off the value to the specified number of decimal places
  value = double.parse(value.toStringAsFixed(decimalPlaces));
}

print(value); // prints 0.0003

Leave a Reply