[java] Printing a double to 2 decimal places in Java 1.4

Started by
17 comments, last by Son of Cain 17 years, 11 months ago
Half-dead subforum?
Ok dude, do not take the time to register. We appreciate your visit, and thanks for sharing those amazing lines of bean shell script.
a.k.a javabeats at yahoo.ca
Advertisement
I don't understand why people don't register.

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

>Half-dead subforum?

Low activity.

>We appreciate your visit, and thanks for sharing those amazing lines of bean shell script.

Its a valid solution for the problem. There is no reason for getting sarcastic.

>I don't understand why people don't register.

Its not required for answering questions. Well, dont worry about it. I wont come back.
.append((Math.rint(a * 100) / 100);

should work well (kinda).

DecimalFormat is supposed to be used in internationalization, not as a simple dirty method for programmers.

of course you can also do
if(a > 0){
a += e;
} else {
a -= e;
}

.print((double) ((int) (a * 100)) / 100D);
No, I'm not crazy, but please replace this:
if(a > 0){a += e;} else {a -= e;}


With this:
a = (a > 0) ? a += e ; a -= e;


;)

Son Of Cain



a.k.a javabeats at yahoo.ca
Quote:Original post by Son of Cain
With this:
a = (a > 0) ? a += e ; a -= e;

That doesn't compile, I think you meant this?
a = (a > 0) ? a += e : (a -= e);


But even that can be rewritten into this:
a += (a > 0) ? e : (-e);


Yes, yes, my typo, and your version is even better optimized! =D
a.k.a javabeats at yahoo.ca
Quote:Original post by Son of Cain
Yes, yes, my typo, and your version is even better optimized! =D


If by better optimized, you mean more difficult to read, then yes.
What is with programmers' facinations with making code so obfuscated? I've yet to see anything that makes it any faster.
Isn't the saying "Premature optimization is the root of all evil"?
In this particular case, it has to do with the way bytecodes are generated for the expression (don't ask me the details, I've just been told the ternary operator translates into better bytecode than if/else to attribute value to a variable). And also, I don't find it hard to read - any average programmer knows about the ternary conditional operator, there's nothing fancy or hacky about it...

Perhaps the term "optimization" may be exagerated alright, but definetely, I'd prefer the one line version rather than the five lines one. Seems like cleaner and clearer code to me.

Either way, my personal opinion. Some might find easier to read the entire if/else, it's up to what you feel to be the better (as long as it doesn't hurt your code logic, anyway =).

Son Of Cain
a.k.a javabeats at yahoo.ca

This topic is closed to new replies.

Advertisement