Home > Software engineering >  How do I round only millions in flutter?
How do I round only millions in flutter?

Time:01-11

The rule is if value >= 500,000 it will be rounded up to 1,000,000, if the value < 500,000 it will be rounded down to 000,000
Here an example, if I have value like 4,843,820,00 it will be rounded up to 4,844,000,000
If I have value like 1,136,362,500 it will be rounded down to 1,136,000,000
If I have value like 1,500,000 will be rounded up to 2,000,000 & if I have like 1,450,000 it will be rounded down to 1,000,000

Here is what I tried

String kmbGenerator(number) {
    if (number > 999 && number < 99999) {
      int resulta = (number / 1000).round();
      return "$resulta,000";
    } else if (number > 99999 && number < 999999) {
      int resulta = (number / 1000).round();
      return '${resulta.toStringAsFixed(0)},000';
    } else if (number > 999999 && number < 999999999) {
      int resulta = (number / 1000000).round();
      return "$resulta,000,000";
    } else if (number > 999999999) {
      int resulta = (number / 1000000000).round();
      return "$resulta,000,000,000";
    } else {
      return number.toString();
    }
  }

CodePudding user response:

Divide by one million, round, then multiply by one million:

int roundMillions(int value) {
  return (value / 1e6).round() * 1000000;
}

main() {
  void test(int value) {
    print('rounded $value to ${roundMillions(value)}');
  }
  test(4843820000);
  test(1136362500);
  test(1500000);
  test(1450000);
}

Output:

rounded 4843820000 to 4844000000
rounded 1136362500 to 1136000000
rounded 1500000 to 2000000
rounded 1450000 to 1000000

CodePudding user response:

Before you format round it using num.round() for example if you want to round to millions :

double n = 29971800;
double roundTo = 1000000; //million
print((n/roundTo).round()); //prints 30

you can either multiply it by million and format it or just convert to String and add ',000,000'

CodePudding user response:

another way is using ~/ and multiplying to million example (123456789~/1000000) * 1000000

use this function

int roundMillion(int val) => (val~/1000000) * 1000000;
  • Related