dart

I want to replace part of the integer number first number with 1 and next 4/5 numbers with 0


I want to replace part of the ntiger number first number with 1 and next 4/5 numbers with 0. No changed in first number is 0.

For example,

  1. I'm getting 8123456789 from backend, but I want to display it as 1000056789.
  2. I'm getting 9665789456789 but I want to display it as 1000009456789.

Would like to take decision number of changing numbers(chracter) with a logic like if user start with A then would like to change first 6 numbers or if user start with B then would like to change first 5 numbers.


Solution

  • I don't fully understand the logic you are looking for but see this an example of the approach you can use to make the thing you actually want.

    I recommend first splitting your number into a List<String> where each digit are represented as a character. By doing so, it makes it a lot simpler to modify individual digits and we can later on join them back to a number.

    void main() {
      print(fixNumber(8123456789, amountOfZeroes: 4));    // 1000056789
      print(fixNumber(9665789456789, amountOfZeroes: 5)); // 1000009456789
    }
    
    int fixNumber(int number, {required int amountOfZeroes}) {
      List<String> digits = number.toString().split('');
      digits[0] = '1';
      
      for (var i = 1; i <= amountOfZeroes; i++) {
        digits[i] = '0';
      }
      
      return int.parse(digits.join());
    }