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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.