1

I need to check if a number entered contain

1.more than two digit after decimal

2.decimal at first place (ex:.2345)

3.decimal at last place (ex:2345.)

How to do this using javascript.

2
  • How can a NUMBER have a decimal at the front and end? I think your meant to ask about strings. Commented Dec 8, 2010 at 13:37
  • Is this part of form validation? Commented Dec 8, 2010 at 13:40

4 Answers 4

2
len = number.length;
pos = number.indexOf('.');

if (pos == 0)
{
  //decimal is at first place
}
if (pos == len - 1)
{
  //decimal is at last place
}
if (pos == len - 3)
{
  //more than two digit after decimal
}
Sign up to request clarification or add additional context in comments.

3 Comments

.length is a property, not a method. Nice and fast apprach, however.
Probably should use else...if so as to not test multiple times.
use pos < len - 3. Now it can have only 2 decimals.
2
var reg = /\d+(?:\.\d{2,})?/;

if ( reg.test(number) )
    alert('Correct format!');

Not sure whether you'd allow decimals only (i.e. without the period) but if, that regexp should be sufficient.

Good luck.

3 Comments

Why would he need luck? Is your code that fragile? ;) +1 for the correct answer.
Good luck with his effort to validate user input, that is.
You're right about that. One needs to be very careful with user input.
1
function check_number(number) {
    var my_number = String(number);
    var place = my_number.indexOf(".");
    if(place == 0) return "first";
    else if(place == (my_number.length - 1)) return "last";
    else if(place == (my_number.length - 3)) return "third to last";
}

1 Comment

@Shakti Singh, you beat me to the answer.
0
var number = "3.21";
if(/[0-9]{1,}\.[0-9]{2,}/.test(number)) {
  //valid
}

4 Comments

I think number should be a string here. Besides that, .test() is a method of the RegExp object. You should use .match() or modify your code so that your regular expression is in front.
Ah yes, thanks for pointing that out. Can you only pass a regex on strings in js?
I am not sure if i understand what you mean, but .match() is a method of String. You can use it to do it the other way around: "some string".match(/some/)
Does it matter? Is match better compared to test?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.