# Thread: How to tell if number has decimal

1. ## How to tell if number has decimal

Hi,

I have a javascript which adds together certain numbers of currency from user input. Ordinarily there won't be any decimal places required, so I'm converting the values using 'parseFloat' which seems to do the trick in displaying the numbers as simple round values without decimals.

However, one field from the user input allows input in amounts of 0.50 to be inserted. After a parseFloat, these values are converted to a single decimal place (e.g. 0.5). I need 2 decimal places because these are currency values.

The problem is that I don't want everything to be rounded to 2 decimal places, just those values that have a decimal.

The calculations can all be done behind the scenes as it is, but I need to display all of the user input values on screen too, for which I need those which have a decimal place to be rounded to 2 decimal places and those without a decimal to remain decimal free. So the user may see something like:

Input value 1 was: 720
Input value 2 was: 10
Input value 3 was: 20.50
Total value is: 750.50

So basically I need to do something like this:

Code:
```var exampleValue = parseFloat(20.50);

if (exampleValue has decimal){
exampleValue = exampleValue.toFixed(2);
}```

Obviously "if (exampleValue has decimal){" isn't proper Javascript - that's where I'm stuck. How do I find if the value has a decimal? From there I can either convert it toFixed (if it has a decimal) or leave it as a parseFloat value without any decimals.

Thanks folks...

2. Well maybe theres an easier way but you could create a var = the number toFixed(0). Subtract that from your number and if the result is > 0 then it has a decimal.

3. Code:
`if (Math.floor(exampleValue) < exampleValue || Math.ceil(exampleValue) < exampleValue) {}`
This won't work if you have a value like 5.00
Works properly with negative numbers.

4. Thanks,

This seems to work perfectly (slightly modified from the suggestion above to deal with negatives) :

Code:
```if (exampleValue.toFixed(2) - exampleValue.toFixed(0) != 0){
exampleValue = exampleValue.toFixed(2);
}```
Thanks again!

5. how about the modulus operator:
Code:
`if((num1 &#37; num2)>0){alert('number is a decimal');}`
never mind, i don't think that will work either...

6. exampleValue = (parseInt(num,10) != parseFloat(num,10) ? parseFloat(num,10).toFixed(2) : parseInt(num,10);

7. exampleValue = num &#37; 1 ? num.toFixed(2) : num;

8. Code:
```Number.prototype.fixDecimal= function(){
return Math.floor(this)< this? this.toFixed(2): this;
}

var n= 134.10

9. One more for the list of options:
Code:
`exampleValue = num &#37; 1 && num.toFixed(2) || num;`
Strange but true.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•