I tried getting some help from stack and l can across this Python code
I would like to know how to convert this into dart and use it to get ordinal numbers
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4])
I tried getting some help from stack and l can across this Python code
I would like to know how to convert this into dart and use it to get ordinal numbers
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4])
Try with this
void main() {
for(int i =1; i<=100;i++){
print("$i${ordinal(i)}");
}
}
String ordinal(int number) {
if(!(number >= 1 && number <= 100)) {//here you change the range
throw Exception('Invalid number');
}
if(number >= 11 && number <= 13) {
return 'th';
}
switch(number % 10) {
case 1: return 'st';
case 2: return 'nd';
case 3: return 'rd';
default: return 'th';
}
}
output: 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th ..................
Resuable version of accepted answer.
main() {
print(toOrdinal(3));
// -> 3rd
print(ordinalGenerator(end: 1000));
// -> [1st, 2nd, 3rd, 4th,..., 1000th]
print(ordinalGenerator(start: 7, end: 14));
// -> [7th, 8th, 9th, 10th, 11st, 12nd, 13rd, 14th]
}
List ordinalGenerator({int start = 1,required int end}) {
if (start < 1) throw Exception('Start Number Can\' be less than 1');
if (start > end) throw Exception('Invalid Range');
return List.generate(
end - (start == 1 ? 0 : start - 1),
(index) => toOrdinal(index + start),
);
}
String toOrdinal(int number) {
if (number < 0) throw Exception('Invalid Number');
switch (number % 10) {
case 1:
return '${number}st';
case 2:
return '${number}nd';
case 3:
return '${number}rd';
default:
return '${number}th';
}
}