0

Hmm Iv tried but they do not seem to work unless im going wrong somewhere in explaining it. I appreciate the fast responses!

Let me try again with a different (better example)

age can be entered as numbers. Now sex the user is only going to enter male or female. So male=200 and female=100

These need to be converted before they can be used as a value 2

function add() {

So i do need to convert them to figures to run the formula. Sorry if I have not explained well.

  • If your question is "is it possible", then the answer is yes. – j08691 Nov 25 '13 at 21:22
  • Input with the type `number`, and you're asking for letters ? – adeneo Nov 25 '13 at 21:22
  • This is pretty similar: http://stackoverflow.com/questions/7802286/generic-way-to-convert-number-words-to-numbers-e-g-first-to-1st – DACrosby Nov 25 '13 at 21:25
  • 1
    possible duplicate of [Javascript: Words to numbers](http://stackoverflow.com/questions/11980087/javascript-words-to-numbers) – drneel Nov 25 '13 at 21:27

3 Answers3

2

If you want to convert "8" to 8:

var age = +$("#age").val();

This will convert the value in #age to a number. You don't need jQuery to do the conversion, but you can use jQuery's .val() for taking the value out of <input>.


If you want to convert "eight" to 8:

First of all, change the type from number to text.

If you want to convert a number written in English to a number, you can use an Object.

var nums = {
    "one": 1,
    "two": 2,
    ...
};
var age = nums[$("#age").val().toLowerCase()];

However this is greatly not recommended because you will have to create an entry for every number you accept.

A better approach would be separating the ones and the tens so on and so forth, but you will have to deal with special cases such as "eleven", "fifty" and invalid inputs: https://stackoverflow.com/a/12014376/283863


Fun fact

Interestingly, it is possible to do the other way around (Number to Word) in modern browsers:

var number = 10;
number.toLocaleString("zh-Hans-CN-u-nu-hanidec");  //it supports many languages,
                                                   //including Chinese.
Community
  • 1
  • 1
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
0

Use a map

var numbers = {
    'one'   : 1,
    'two'   : 2,
    'three' : 3,
    'four'  : 4,
    ... etc
}

var age = numbers[ $('#ageinletter').val() ];

with a text input

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

Use the Number() function.

var age = Number($('#age').val());

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number

This is only for "1" => 1, not "one" => 1. I'm not sure if there is an out-of-the-box way to convert from text to numbers.

Justin Ryder
  • 757
  • 9
  • 17