简体   繁体   中英

Set format for decimal number

I am validating certain input by using RegEx in jQuery which is working as expected. I want to add an addition where it adds 0 prior to decimal point if user don't add it.

For example,

.50 to 0.50
-.50 to -0.50

How to do that?

Code:

 $(document).ready(function() { $('#btnval').click(function() { var floatRegex = new RegExp(/^-?[0-9]+([\\,|\\.]{0,1}[0-9]{2}){0,1}$/); var currentSetTextBoxValue = $('#txtval').val(); //alert(currentSetTextBoxValue); var validateInput = floatRegex.test(currentSetTextBoxValue); alert(validateInput); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input type="text" id="txtval" /> <input type="button" value="Get textbox Value" id="btnval" />

Change [0-9]+ to [0-9]* , so that it allows zero digits instead of requireing at least one.

 $(document).ready(function() { $('#btnval').click(function() { var floatRegex = new RegExp(/^-?[0-9]*([\\,|\\.]{0,1}[0-9]{2}){0,1}$/); var currentSetTextBoxValue = $('#txtval').val(); //alert(currentSetTextBoxValue); var validateInput = floatRegex.test(currentSetTextBoxValue); alert(validateInput); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input type="text" id="txtval" /> <input type="button" value="Get textbox Value" id="btnval" />

You can fix the value like this if you need to convert it later:

if(currentSetTextBoxValue.indexOf('.') === 0){
    currentSetTextBoxValue = '0' + currentSetTextBoxValue;
}
if(currentSetTextBoxValue.indexOf('.') === 1 && currentSetTextBoxValue.indexOf('-') === 0){
    currentSetTextBoxValue = '-0.' + currentSetTextBoxValue.split('.')[1];
}

https://jsfiddle.net/str59woa/3/

You can replace the input using regex! This regex looks for . or -. at the beginning of the string and it will replace it by 0. or -0. depending on what it found, if it does not match the string will be the same.

 $(document).ready(function() { $('#btnval').click(function() { var floatRegex = new RegExp(/^-?[0-9]+([\\,|\\.]{0,1}[0-9]{2}){0,1}$/); var currentSetTextBoxValue = $('#txtval').val().replace(/^(\\-)?\\./, "$10."); //alert(currentSetTextBoxValue); var validateInput = floatRegex.test(currentSetTextBoxValue); alert(validateInput); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input type="text" id="txtval" /> <input type="button" value="Get textbox Value" id="btnval" />

https://jsfiddle.net/punsm9o0/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM