I'm thinking about the usage of percent, example, in margins.

We can use overlay to separate our layout by DPI sizes, but why can't we use percentage?

Something like that:

Display display = getWindowManager().getDefaultDisplay();

float width = display.getWidth();
float height = display.getHeight();

//20% of left margin
float imageMarginLeft = ( width * 20 ) / 100;

And then set this margin to the image, or whatever element.

Is this bad?


You can simplify math whenever possible. No reason to multiply by 20 then divide by 100. Just multiply by .20. If you needed a result that was twenty percent in addition to 100 percent of what you already had you could multiply by 1.2. It saves a process making your code just a tad more efficient!

| improve this answer | |
  • 1
    \$\begingroup\$ The compiler will probably optimize the expression, but even if it doesn't, the efficiency gain is negligible. \$\endgroup\$ – S.L. Barth - Reinstate Monica Aug 3 '12 at 7:49
  • \$\begingroup\$ @S.L. Barth-Nowadays your right but people used to count processes, and I was taught that inefficient code should never be a supplement for efficient code. Yes, this one computation will never be recognized, but discounting simple math procedures over a million lines of code is arguably incorrect. And for that matter why not? I look at that line and think well that's not very sharp, but to each their own I suppose. \$\endgroup\$ – ChiefTwoPencils Aug 3 '12 at 7:51
  • 2
    \$\begingroup\$ Seems we've been taught different things then. I was taught that "It's easier to make correct code go fast, than to make fast code correct". Either way, I do agree that it's good to simplify maths - in general it makes the code more legible, and it may prevent rounding errors. \$\endgroup\$ – S.L. Barth - Reinstate Monica Aug 3 '12 at 8:09
  • \$\begingroup\$ @S.L.Barth- Perfect, that was my true intent in passing the info, the so called efficiency was more of thing to continually think about. I like the quote! Real similar to "cheap blanks aren't good and good blanks aren't cheap"!) \$\endgroup\$ – ChiefTwoPencils Aug 3 '12 at 8:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.