Home > Mobile >  Flutter - convert string to int without losing leading zero
Flutter - convert string to int without losing leading zero

Time:01-09

I'd like to convert the clock time (e.g., '05:34') to integer without losing the leading zero (e.g., 0534).

Currently I can convert it to int but it results in (534). I use this code (from this answer):

int tmpInt = int.parse(tmpString.replaceAll(RegExp(r'[^0-9]'), ''));

EDIT: I need to do this as these values will be sent as raw integers to another dump device to display the time.

CodePudding user response:

If you just want to remove the : from the string and keep the leading zero, you can use the replaceAll function like this:

String clockTime = '05:34';
clockTime = clockTime.replaceAll(':', '');
print(clockTime);  // Outputs: "0534"

If you want to keep the leading zero and still have the integer value as 0534, you can pad the string with a zero at the beginning if the length of the string is less than 4. Here's how you can do it:

String clockTime = '05:34';
clockTime = clockTime.replaceAll(':', '');

if (clockTime.length < 4) {
  clockTime = '0'   clockTime;
}

print(clockTime);  // Outputs: "0534"

// Use the original clockTime string to display the time with the leading zero
print('The time is: $clockTime');  // Outputs: "The time is: 0534"

int timeInInt = int.parse(clockTime);
print(timeInInt);  // Outputs: 534

This way, you'll have a string with the leading zero, and the integer value will be the same as the original time with the : removed.

Note: Converting/parsing string to int will always remove leading zero. There is no way to keep the leading zero after converting the string to an integer, because integers do not have leading zeros.

However, you can keep the original clock time string and use it whenever you need to display the time with the leading zero as mentioned above. You can also convert the string to an integer when you need to perform arithmetic operations or comparisons on the time value.

  • Related