Question

Is there any inbuilt js/jquery function that converts 1 to first, 2 to second, 3 to third... etc.?

ex:

Num2Str(1); //returns first;
Num2str(2); //returns second;

I dont want to write a function for 100 numbers. Please help.

Était-ce utile?

La solution

There is no inbuilt function for it.

I did write one for up to 99:

var special = ['zeroth','first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth'];
var deca = ['twent', 'thirt', 'fort', 'fift', 'sixt', 'sevent', 'eight', 'ninet'];

function stringifyNumber(n) {
  if (n < 20) return special[n];
  if (n%10 === 0) return deca[Math.floor(n/10)-2] + 'ieth';
  return deca[Math.floor(n/10)-2] + 'y-' + special[n%10];
}

// TEST LOOP SHOWING RESULTS
for (var i=0; i<100; i++) console.log(stringifyNumber(i));

DEMO: http://jsbin.com/AqetiNOt/1/edit

Autres conseils

You could create a numberbuilder:

You will need to create a foolproof way to convert the single digits by power to a string.

1234 -->1(one)*10^3(thousand)+2(two)*10^2(hundred)+3(three)10(ten)+4(four)(one)
==> one thousand two hundred th irty four th

123456 --> one hundred tw enty three thousand four hundred fi fty six th

if you are wondering about the notation: I tried to split this up in the single decision steps you need to make

the rules for building repeat every three digits. The rest is up to you.

Oh and before I forget: there is only "3" exceptions to the th-rule. one, two and three.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top