aaronhuisinga
aaronhuisinga

Reputation: 299

Adding a 0 before decimal entered in input?

I'm attempting to finish up a quick form using jQuery that needs to add a 0 before a decimal point if the decimal is the first char entered in the input.

For example, .25 would become 0.25 before the form is submitted. However, 2.05 would stay as 2.05, and no 0 would be added.

Is there a simple function here that could help me out? I'd rather not write something long and detailed if it's not necessary.

Also, here is the input box that I am asking for help with, for reference

<input type="number" name="dailygain" id="dailygain" />

Upvotes: 4

Views: 6597

Answers (5)

vol7ron
vol7ron

Reputation: 42109

Multiply by 1 (*1) to make it numeric.

If you make it a number, it'll do it for you automatically; formatting based on your systems locale.

Example:

var x = '.25';
console.log( x*1 );  // 0.25

The same can be accomplished with a unary plus (e.g., console.log( +x ); )

Upvotes: 1

Roko C. Buljan
Roko C. Buljan

Reputation: 206111

$("input[name=dailygain]").keyup(function(){
   var val = this.value;
   if(val.charAt(0) === '.'){
     this.value = ('0'+val); 
   }
});

http://jsbin.com/ofivun/2/edit

Upvotes: 0

adeneo
adeneo

Reputation: 318202

parseFloat is probably more suited, but anyway :

$('#dailygain').on('keyup', function() {
    if (this.value[0] === '.') this.value = '0'+this.value;
});

FIDDLE

Upvotes: 0

Ashley Strout
Ashley Strout

Reputation: 6258

Put this in a function run onsubmit.

var num=$("#dailygain").val(); //read the number from the textbox
num=num.toString(); //convert that number to a string
if (num.charAt(0)==".") //check if the string starts with a period
    num="0"+num; //if so, add a 0 in front of it
$("#dailygain").val(num); //write the number back to the tb

Upvotes: 0

VisioN
VisioN

Reputation: 145398

You can use parseFloat function to format float numbers.

var el = document.getElementById("dailygain");
el.value = parseFloat(el.value);

Upvotes: 9

Related Questions