Format Number in Flutter

Asked

Viewed 9,962 times

1

I have the following function that calculates and saves 2 data in my database, but I want to format kwhAparelho and totalAparelho in a way that does not cause periodic tithes and preferably this way ##,## or ##. ##, what’s the best way to do it?

void _calculoAparelho() {
double quantidade = double.parse(qtdControlled.text);
double horadia = double.parse(horadiaControlled.text);
double diames = double.parse(diamesControlled.text);
double potencia = double.parse(potenciaControlled.text);
double kwh = double.parse(controllerkwh.text);
// calculo kwh
double kwhAparelho = (potencia * horadia * diames * quantidade / 1000);
note.consumokwh = '$kwhAparelho';
// valor em reais
double totalAparelho = (kwhAparelho * kwh);
note.gasto = '$totalAparelho';  }

1 answer

8


That question is more related to Dart than Flutter itself.

I don’t know if you want to round the value to the decimal places, or simply format the number to obey the mask by ignoring the decimal places.

For example the number 0.18941 and the mask ##,##

  • Just formatting: 00.18
  • Rounding and formatting: 00.19

The documentation is your friend, if you take a look at this method toStringAsPrecision() of the class num, you can pass an int value of accuracy and it will give you a value formatted with the required accuracy.

Using it 0.18941.toStringAsPrecision(2)

  • The return is: 0.19

Run an example on Dartpad

Now to format this value so that on both sides of the floating point (integer value and decimal value) obey the mask, the class can be used Numberformat. This one needs to be imported from the package lntl, and because of that does not run by Dartpad, but follows the code:

import 'package:intl/intl.dart';

main() {
  NumberFormat formatter = NumberFormat("00.00");
  double initialValue = num.parse(0.18941.toStringAsPrecision(2));
  double value = 0.19;

  print(formatter.format(initialValue));
  print(formatter.format(value));
}

The result of the code will be:

0.19

00.19

You need to add the package dependency to pubspec.yaml

dependencies:
  intl: ^0.15.7

Browser other questions tagged

You are not signed in. Login or sign up in order to post.