Flutter int value if first digit is not zero I want to get first value
for example
int x=123 result =1;
another example int y=234; result=2;
if the first value is zero I want to get the second value
for example int a=023; result=2;
another example int b=098; result=9;
how can i do this using dart?
CodePudding user response:
There surely is a more mathematical way, but one way to do this is to convert the int
to a String
, get the first character and parse it back to int
:
var numbers = [
1234,
567,
89,
];
for(var number in numbers) {
var firstNumber = int.parse(number.toString()[0]);
print(firstNumber);
}
Output :
1
5
8
CodePudding user response:
This will give you the first non-zero digit. Assuming you get your number as a String
. Otherwise it is pointless because the int value = 0123
is the same as int value = 123
.
String yourNumber = "0123";
final firstNonZero = int.tryParse(yourNumber.split('').firstWhere((element) => element != '0', orElse: () => ''));
print(firstNonZero);