Jonny
Jonny

Reputation: 1

Int String format problem

I'm returning this, it is similar to how you percieve dollars, $"32.95" etc. I calculate it in cents which is an int, but the problem is the second half cuts off the 10s of cents part if the number is less than that. For example if I have "32.08" it returns as "32.8". Any ideas ? i know i need an if but i cant think how to write it.

public String toString()
{
    return (cents / 100)+ "." + (cents % 100);
}

Upvotes: 0

Views: 849

Answers (8)

Anon.
Anon.

Reputation: 60013

The quick hack:

return String.format("%d.%02d", cents/100, cents%100);

Upvotes: 3

duffymo
duffymo

Reputation: 308938

Where's the abstraction? Java's an object oriented language. Wouldn't it be a better idea to encapsulate all that implementation detail in a Money class and hide it from clients?

Upvotes: 0

irreputable
irreputable

Reputation: 45443

(""+(100+cents%100)).substring(1) // LOL

(cents / 100)+ "." + (cents /10 %10) + (cents % 10); // <<== OK

Upvotes: 0

GrayWizardx
GrayWizardx

Reputation: 21191

NumberFormat nf=NumberFormat.getInstance(); // Get Instance of NumberFormat
nf.setMinimumIntegerDigits(5);  // The minimum Digits required is 5

return (cents / 100)+ "." + nf.format(cents % 100);

That should do it, been a while since I did java.

Upvotes: 0

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

So, 32.08 % 100 is 8 not 08. You could of course add in a "0" for values less than 10.

However, you might want to think about using java.text, in particular NumberFormat, DecimalFormat and MessageFormat. java.util.Formatter and "printf" might be more appropriate if you are attempting to write machine readable text.

Upvotes: 0

Jan Gorzny
Jan Gorzny

Reputation: 1772

You could always check if cents % 100 is less than 10, and if it is, add another 0. There's probably a more elegant solution though.

Upvotes: 0

miku
miku

Reputation: 188114

You can use http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.

String pattern = "$###,###.###";
double value = 12345.67;
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
// => 12345.67 $###,###.### $12,345.67

Upvotes: 6

Francis Upton IV
Francis Upton IV

Reputation: 19443

Use the BigDecimal class, that's what it's for.

Upvotes: 0

Related Questions