Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading