Hi guys, 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. eg/ 32.08. Any ideas ? i know i need an if but i cant think how to write it.

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

Dani AI

Generated

— the integer-cents approach is the right idea. The symptom you saw (32.08 becoming 32.8) is just missing left padding for the cents. was on the right track with padding, but their posted if/else ends up prepending the "0" in both branches, so it does not actually fix the formatting.

A concise, robust way is to format the two integer parts with a fixed two-digit width for cents. Handle the sign separately so negative values format as "-32.08", and use absolute values for the two parts to avoid the negative remainder problem Java has with %. Example:

int absCents = Math.abs(cents);
int dollars = absCents / 100;
int centPart = absCents % 100;
String sign = cents < 0 ? "-" : "";
return String.format("%s%d.%02d", sign, dollars, centPart);

Notes and caveats:

  • This keeps everything in integer arithmetic so there is no floating-point rounding.
  • Math.abs(Integer.MIN_VALUE) overflows; if your code could see Integer.MIN_VALUE, use long or guard for that edge case.
  • For locale-aware currency symbols, grouping, or rounding rules use the currency-related API, but for a simple cents/dollars display this integer-based formatting is simpler and safer.

See the Java Formatter documentation for the %02d specifier details: java.util.Formatter javadoc.

Hi guys, 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. eg/ 32.08. Any ideas ? i know i need an if but i cant think how to write it.

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

You can either do it by using if then else statement by using this

if((cents%100) < 10)
    return (cents / 100)+ "." + "0"+(cents % 100);
else
    return (cents / 100)+ "." + "0"+(cents % 100);

You can also you use a Numberformat class.

import java.text.*;
NumberFormat formatter = new DecimalFormat("0.00");
return (formatter.format(cents/100.0));
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.