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';
}
}
Using extensions, the code below can be used with any int type. Since ordinals are based on the last figure of a digit; this int extension takes the integer value and converts it to string Next, it gets the last index of said string and uses that to determine the ordinal.
extension NumberParsing on int {
String toOrdinalString() {
if ((this < 0)) {
//here you change the range
throw Exception('Invalid number: Number must be a positive number');
}
if (this == 0) {
return '0';
}
String stringValue = toString();
switch (stringValue[stringValue.length - 1]) {
case '1':
return stringValue + 'st';
case '2':
return stringValue + 'nd';
case '3':
return stringValue + 'rd';
default:
return stringValue + 'th';
}
}
}
// Usage:
int someIntValue = 25;
someIntValue.toOrdinalString();
//Output:
25th
// Generate Ordinals from 1 to 100
for(int i =1; i<=100;i++){
print(i.toOrdinalString());
}
I made a package for this using the native platform libraries.
https://pub.dev/packages/ordinal_formatter
final ordinalString = await OrdinalFormatter().format(2) ?? '';
// -> 2nd
final localisedOrdinalString = await OrdinalFormatter().format(2, 'en_US') ?? '';
// -> 2nd