Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append an extra 'Zero' after decimal in Javascript

Hye, Iam new to javascript working with one textbox validation for decimal numbers . Example format should be 66,00 .but if user type 66,0 and dont type two zero after comma then after leaving text box it should automatically append to it .so that it would be correct format of it . How can i get this .How can i append ?? here is my code snippet.

 function check2(sender){
           var error = false;
           var regex = '^[0-9][0-9],[0-9][0-9]$';
           var v = $(sender).val();
           var index = v.indexOf(',');
           var characterToTest = v.charAt(index + 1);
           var nextCharAfterComma = v.charAt(index + 2);

            if (characterToTest == '0') { 

              //here need to add 
            }
}
like image 526
Somi Meer Avatar asked Nov 07 '11 08:11

Somi Meer


2 Answers

Use .toFixed(2)

Read this article: http://www.javascriptkit.com/javatutors/formatnumber.shtml

|EDIT| This will also fix the issue if a user types in too many decimals. Better to do it this way, rather than having a if to check each digit after the comma.

like image 185
OptimusCrime Avatar answered Oct 30 '22 16:10

OptimusCrime


.toFixed() converts a number to string and if you try to convert it to a float like 10.00 then it is impossible.

Example-

  1. 10.toFixed(2) // "10.00" string
  2. parseFloat("10.00") // 10
  3. Number("10.00") // 10
like image 44
Karan Attri Avatar answered Oct 30 '22 15:10

Karan Attri