0
public int dpToPx(int dp, Context context) {
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));       
    return px;
}

taken from here

public int dpToPx(float dp, Context context) {
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, displayMetrics);
    return px; 
}

taken from here

What are the differences between these two?

Community
  • 1
  • 1
user6265154
  • 353
  • 1
  • 6
  • 19
  • 1
    I've edited the snippets to be more similar, so any comparing is easier. I've also removed the opinion based "which one is better" question – Tim Aug 31 '16 at 08:12

1 Answers1

1

the difference is in rounding value and truncating value.

Rounding of 4.6 will result in 5
Truncating 4.6 will result in 4.

It really does not relate to Android, and basically is Algebra, not a programming question.

Vladyslav Matviienko
  • 10,610
  • 4
  • 33
  • 52