Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android-Convert dp units to pixel units with factor 0.5f

I read here about converting dp units to pixel units. But I cant understand the 0.5f. Where does this number come from and what is the use of it?

// The gesture threshold expressed in dp
private static final float GESTURE_THRESHOLD_DP = 16.0f;

// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale

mGestureThreshold = (int) (GESTURE_THRESHOLD_DP * scale + 0.5f);

// Use mGestureThreshold as a distance in pixels...
like image 984
Nick Avatar asked Dec 22 '25 03:12

Nick


2 Answers

Casting floating point numbers to integer will floor them. That 0.5f is to round the number:

x = (int) 3.9
print x // 3



x = (int) 3.9 + 0.5f
print x // 4
like image 182
Azad Avatar answered Dec 24 '25 11:12

Azad


Its to round things. Scale may be a decimal (like 1.5). This means the product may not be a whole number. Adding .5 then converting to int ensures that the number rounds up if the number is more than halfway between two integers, and down if its less than halfway.

like image 27
Gabe Sechan Avatar answered Dec 24 '25 10:12

Gabe Sechan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!