Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a double value has no decimal part [duplicate]

Tags:

java

double

I have a double value which I have to display at my UI. Now the condition is that the decimal value of double = 0 eg. - 14.0 In that case I have to show only 14 on my UI. Also, the max limit for characters is 5 here.

eg.- 12.34 the integer value can be no bigger than 2 digits and so is the decimal value for our double.

What could be the best way of doing this?

like image 403
Ankit Avatar asked Apr 12 '13 05:04

Ankit


People also ask

How do you check if a double value has no decimal part?

Compare two values: the normal double, and the double after floor ing it. If they are the same value, there is no decimal component.

How do you check if a number has no decimals?

function number_test(n) { var result = (n - Math. floor(n)) !== 0; if (result) return 'Number has a decimal place.

How do you find the decimal part of a double?

var decPlaces = (int)(((decimal)number % 1) * 100);

How do you get rid of decimal point in double value?

Truncation Using Casting If our double value is within the int range, we can cast it to an int. The cast truncates the decimal part, meaning that it cuts it off without doing any rounding.


2 Answers

You could simply do

d % 1 == 0 

to check if double d is a whole.

like image 186
Lone nebula Avatar answered Oct 12 '22 16:10

Lone nebula


double d = 14.4; if((d-(int)d)!=0)     System.out.println("decimal value is there"); else     System.out.println("decimal value is not there"); 
like image 41
Subhrajyoti Majumder Avatar answered Oct 12 '22 15:10

Subhrajyoti Majumder