decimalpoint

I have a text field where users enter whole numbers.  What I want to do is to automically add a decimal point and two zeros to the end of the number (ex: 123.00) when it is manually entered.  For some reason, it is too much work for users to simply add .00 manually.
rahoo ckAsked:
Who is Participating?
 
Dorababu MSenior Software EngineerCommented:
You can write a function like this
$(document).ready(function () {
$('#some_num').bind('change', function(){
    this.value = ConvertToDecimal(this.value);
});
});
function ConvertToDecimal(input) {

    // a negative sign comes before any digit
    var is_negative = /^[^0-9]*\-/.test(input)

    // remove anything that is not a digit or decimal point
    var digits = input.replace(/[^0-9\.]/g, '');

    // find the first decimal point
    var decimal_point = digits.indexOf('.');

    // no decimal point, don't worry about inserting one
    if(decimal_point == -1) decimal_point = digits.length;

    // remove all other decimal points and create a numeric string
    var clean = (is_negative?'-':'') + digits.substr(0, decimal_point) + '.' + digits.substr(decimal_point).replace(/\./g, '');

    // attempt to turn this into a number data-type
    var number = parseFloat(clean);

    // no digits (not a number) return '0.00'
    if(isNaN(number)) return '0.00';

    // round to two decimal places
    number = Math.round((number*100) / 100);

    // force two digits after the decimal point, convert to string and return it
    return number.toFixed(2)+'';
}

Open in new window


Example fiddle https://jsfiddle.net/DorababuMeka/em2weyqx/

You can also look at this

https://jsbin.com/gosaros/edit?html,js,output
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.