Money Format WTF 22
The reason the DailyWTF is so funny, is that we all secretly identify with it. Here’s my latest WTF.
It happened last night at about 7pm. My wife wanted me to run to the store with her. I wanted to get my tests to pass so I could check in my code. I knew that if I left the code checked out until morning, one of my compatriots would wake up at 3am and change something, and I’d have to do a merge. I hate doing merges!
I needed to write thetoString()
method for my Money
object. I had my tests already. Here they are:
public void testToString() throws Exception {
assertEquals("$3.50", new Money(350).toString());
assertEquals("$75.02", new Money(7502).toString());
assertEquals("$0.01", new Money(1).toString());
assertEquals("$0.00", new Money(0).toString());
}
I quickly wrote the function I knew would work:
public String toString() {
return String.format("$%d.%02d",pennies/100, pennies%100);
}
What can I say. I’m an old C programmer. When the format method showed up in Java 5 I jumped for joy.
Even as I typed this code, something was nagging at the back of my brain. Something was telling me there was a better way. But then, I was interrupted by a huge disappointment.
It didn’t compile. Damn! I forgot I was writing in a Java 1.4 environment. No String.format
!
What to do? What do to?
(Wife: “Bob, are you ready to leave yet? It’s getting late! The store is going to close!)
uncleBob.changeMode(CODE_MONKEY);
I wrote this:
public String toString() {
int cents = pennies % 100;
int dollars = pennies / 100;
return "$" + dollars + "." + ((cents < 10) ? "0" : "") + cents;
}
The tests passed, and I checked in my code and went to the store with my lovely wife.
——-
This morning I woke up, finished reading a book on Quantum Mechanics, read a few blogs, and in general pursued my joyous life of study and work. But somethign was nagging at the back of my brain. Something told me to look in the Java Docs for NumberFormat
.
(sigh). On one screen was the code my monkey brain had written last night. On the other screen was the JavaDoc for NumberFormat. (sigh).
So I sheepishly changed my code to:
public String toString() {
NumberFormat nf = NumberFormat.getCurrencyInstance();
return nf.format(pennies/100.0);
}
Of course I know Beck’s rule: Never let the sun set on bad code.
I really need to find that code monkey and kill it.
May be use NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US); is better, otherwise it will pick the machine locale but actually Sun have make proper research about how people other than US format currency (Well, at least people at Hong Kong) and make silly guess about the format they use.
I have some problems with the code. It doesn’t work.
Hah,that was really funny. I even ordered an essay paper on it.These online essay writers made an excellent essay for me.
I don’t recommend that on any project that needs to work, but I also don’t recommend using a real product to learn your tools.
A very very excellent and informative article there peanut butter cookie
Thanks for sharing such a good article, I like your point of view, this matter sorted out your thoughtful blogger exchange is my honor, I wish I could, and you become good friends, for more a more in-depth exchanges! Georgia Child Care Grants
great article..thanks for the post. http://www.AlliedBuildings.ca
Its an absolute wonderful article. I will surely forward it to my friends.Florida Daycare Forms
Well, my friend made me a website through flash, and he sent it to me, i try to open it in flash and Flash opens then it says ‘Unexpected File Error’ Could someone here please tell me how to fix it! Please!
GHD australia have fairly very rated for rather a few of elements just like pattern durability and ease of use.
@ tips to save money
Maybe the file that he sent you is corrupted. Or the file is not supported with your current flash player.
I wanted to get my tests to pass so I could check in my code. I knew that if I left the code checked out until morning, one of my compatriots would wake up at 3am and change something, and I’d have to do a merge.
No method is available today in the realm of science that enables us to objectively judge that an individual has become competent enough to consent to life-changing decisions. http://educationonlinenow.wordpress.com/2011/01/13/the-many-career-opportunities-in-education/
I recently came accross your blog and have been reading along.I thought I would leave my first comment. I dont know what to say except that I have enjoyed reading.Nice blog.I will keep visiting this blog very often.
Avail $1000 SEO services at Just $180 From The Largest India SEO Services Company in India
Thanks uncle bob its useful…
Okey Oyunu Oyna
It is definitely a good idea to do lots of research when looking for a loan from a bank.
When I at first left a comment I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three notification emails with the same comment. Is there any way you can take away people from that service? Thanks a lot!
It’s different in Scotland. People who come to readings are more interested in literature as such, but the readership in general is really quite diverse. It’s a cliche, but it’s said that people who read my books don’t read any other books, and you do get that element.
Nous attendons les prochaines années, requin tn va créer une moyenne annuelle de près de 2 milliards de dollars cash flow libre, suffisant pour bien soutenir la croissance interne de l’entreprise et les acquisitions externes, et des dividendes stables et rachats d’actions. Valorisation, la croissance et la rentabilité Nous nous attendons à la juste valeur de la Nike a légèrement augmenté à 87 $ par action, correspondant à 17 fois les bénéfices, soit 11 fois EV / EBITDA et le rendement de cash flow libre de 4%. Alors que les coûts des intrants continueront à être les obstacles en suspens dans les prochains trimestres, mais un avenir solide commandes signifiait air max tn dans les derniers trimestres seront mis en place par la dynamique de croissance sous-jacente continue de l’exercice 2012. La capacité de Nike à distinguer les prix devraient être en mesure de soutenir la croissance, ce qui indique généralement la demande croissante et la marge brute. Si la dynamique de croissance actuelle dans les marchés émergents continue, basket et course en Amérique du Nord, les sports de vente de vêtements tendances ne sont pas à l’avenir, Nike exercice 2012, nous avons élevé à un chiffre attentes de croissance des revenus peut être conservatrice. Compte tenu de l’évolution de l’entreprise pour augmenter la pénétration du marché et Converse, Umbro et d’autres acquisitions potentiel inexploité de la marque, nous continuons de maintenir une plus longue période de croissance des revenus de pas cher nike air max Tn élevée à un chiffre avec confiance.
The big high pressure regulator company, offering air cylinder tube,air operated valve,double acting cylinder the safest online trade & Best quality of customer service.
Most of us will delete the SMS file if the iPhone inbox is full. For some of the very important text file, you would like to save it to Mac hard drive and read it later or you need print them. So, why not export the text message to HDD and save it now?