Formatting using javascript

Hi ,

I am trying to validate and format the following input 's using javascipt.Can anyone provide sample code for this.

i/p o/p

789 -----> 789.00
789.1 ----> 789.10
789. ----> 789.00
78965 -----> 789.65
789.12 -----> 789.12

Thanks in advance

You can’t. Input/Output 1 and Input/Output 4 contradict each other. Your behavior has to be consistent to be able to format it properly.

Though personally, I’d defer to server side formatting for this work. Why present something wrong, then change it via javascript. Doesn’t make sense.

Agreed with @DaveMaxwell - there is no way to definitively know if “789” should be “7.89” or “789.00”, unless you can guarantee that every entry will be exactly 5 digits in length.

If all you’re looking to do is make sure that all entered values are formatted for dollar amounts (which that appears to be the case), then you can just use toFixed(x) where x is the number of digits to appear after the decimal point. That will take “789” and make it “789.00”, but it will NOT take “78965” and make it “789.65”, it will make it “78965.00”.



Assuming the number is in a variable called num

while (num > 1000) num /=10;
num = num.toFixed(2);

@felgall , thank you so much.It’s working like a charm…