user1926313
user1926313

Reputation: 11

dealing with decimals

I need help with this decimal problem I have. By making feet and inches on the same textbox. In the case of getting the height of a person in feet(ft), the situation is 5.12ft = 6ft and 5.13 is like unnecessary(not really, I'm just trying to order in feet and inches).

Some will make it a 2 different textbox that will feet and inches respectively. But I want try it with only one textbox that it won't reach 5.12 or in the case of the textbox will only accept up to .11 in inches.

Any help would be appreciated.

Thanks in advance.

Upvotes: 0

Views: 211

Answers (3)

user578895
user578895

Reputation:

One possibility using my jQuery iMask plugin:

$('#i4').iMask({
      type   : 'fixed'
    , mask   : '9\' 99\"'
    , sanity : function( val ){
        val = /([\d ]\' )([\d ])([\d ])\"/.exec( val );

        (val[2]>1) && (val[3]=val[2]) && (val[2]='0');
        (val[2]==1) && (val[3]>1) && (val[3]='1');

        val.shift();
        return val.join('');
    }
})

Demo

Upvotes: 1

John
John

Reputation: 16007

I can't see any way around this besides parsing the string each time you enter a character.

Split your string into feet and inches based on the decimal point, and disallow any characters that result in more than 11 inches.

You also can parse the string when the user is done entering it, and inform her if the form is incorrect or non-sensical.

But another question: Any particular reason you're doing it this way instead of two drop-downs? You can fill the inches one with 0 through 11 and it's straightforward.

Upvotes: 1

paddy
paddy

Reputation: 63481

You generally deal with this by computing the whole part and fractional part separately.

To find the fractional part (0.12), you just subtract the whole part (5) from the original (5.12). And of course multiply by the number of inches in a foot.

var height = 5.12;
var feet = Math.floor(height);
var inches = Math.floor( 12.0 * (height-feet) );

There I've rounded down. If you want to round to the nearest you can do:

var inches = Math.round( 12.0 * (height-feet) );
if( inches == 12 ) {
    feet++;
    inches = 0;
}

Upvotes: 0

Related Questions