Decimal Flutter

Asked

Viewed 1,107 times

0

Gentlemen, good night!

I have a problem in my calculation because it is coming out broken values, Ex: 13,3434

I would like you to leave only 13,34.

Follow the code for better viewing.

Future calculate() {
double precototal1 =
    double.parse(_precoCtrl.text.replaceAll(new RegExp(r'[,.]'), '')) * 12;
double precototal2 =
    double.parse(_precoCtrl1.text.replaceAll(new RegExp(r'[,.]'), '')) * 12;
double unidademl1 =
    double.parse(_unitCtrl.text.replaceAll(new RegExp(r'[,.]'), ''));
double unidademl2 =
    double.parse(_unitCtrl1.text.replaceAll(new RegExp(r'[,.]'), ''));

double difvalor = 0;
double latas = 0;
double litros = 0;
double totlitros = 0;
double diflitros = 0;

setState(() {
  _completed = false;
  _busy = true;
});

return new Future.delayed(const Duration(seconds: 1), () {
  setState(
    () {
      print(formatter.format(precototal2));
      if (precototal1 > precototal2) {
        difvalor = precototal1 - precototal2;
        latas = (difvalor / precototal2);
        litros = (latas * unidademl2);
        totlitros = litros + unidademl2;
        diflitros = (totlitros - unidademl1);
      } else {
        difvalor = (precototal2 - precototal1);
        latas = (difvalor + precototal1);
        totlitros = litros + unidademl1;
        litros = (latas / unidademl1);
        diflitros = (unidademl2 - totlitros);
      }

1 answer

2

From what I understand, your wish is to keep the same number of houses after the decimal point:

12,12345 turns 12,12

0,012345 becomes 0,012

If this is really your case, you can use the method of a: toStringAsFixed

The parameter that this function receives is the number of decimal places, in your case, 2:

var numero = 13.3434;
print (numero.toStringAsFixed(2)); //printa 13.34

This turns your variable into a string. If you want it to stay as double, you can parse it later:

var numero2 = double.parse(numuero.toStringAsFixed(2));
  • Exactly what I was looking for!!! Only in this case, as you can see in the code my double variables are only in the calculate and this is preventing to pass it with the toString

Browser other questions tagged

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