0

I've a piece of Java code from here which converts a number to words, it's working fine but the fraction is always 1 less than it should be, ex. 122.11 is printed 122.10.

Here is piece of code which is doing the calculation. How can I solve this issue?

    String phrase = "122.11" ;
    Float num = new Float( phrase ) ;
    int dollars = (int)Math.floor( num ) ;
    int cent = (int)Math.floor( ( num - dollars ) * 100.0f ) ;
mschmidt
  • 2,740
  • 4
  • 17
  • 31
JAVADEV
  • 51
  • 6

2 Answers2

0
String phrase = " 555243.22" ;
Double num = new Double( phrase ) ;
double dollarsAsDouble =  Math.floor( num ) ;
double val=num - dollarsAsDouble+0.005;
int cent = (int)Math.floor(val * 100.0f ) ;
int dollars=(int) dollarsAsDouble;
System.out.println(cent);//555234
System.out.println(dollars);//22

or:

String phrase = "122.12" ;
String[] val=phrase.split("\\.");
int dollars=new Integer(val[0]);
int cent=0;
if(val.length>1)
    cent=new Integer(val[1]);

System.out.println(cent);
System.out.println(dollars);

or:

String phrase = "555243.22" ;
BigDecimal num = new BigDecimal(phrase);
num.setScale(2, BigDecimal.ROUND_HALF_UP);
BigDecimal result = num.subtract(new BigDecimal(num.longValue()));
System.out.println((int)(result.doubleValue()*100.0)); // 22
System.out.println(num.intValue());//555243
One Man Crew
  • 9,420
  • 2
  • 42
  • 51
0

0.11 cannot be represented exactly in the floating point arithmetic, and ends up being 0.1099999something internally (0.10999999999999943, at least on my machine, but that should be universal). Multiply by 100 and floor it, and you get 10. You can easily circumvent this by rounding the 100-fold number, instead of flooring it, simply by adding 0.5 to the number you want to round. And, you can skip the Math.floor(), as casting the number to int already does what you want:

int cent = (int)( ( num - dollars ) * 100.0f + 0.5f) ;
Igor F.
  • 2,649
  • 2
  • 31
  • 39
  • this solution is giving wrong results when the number gets bigger, ex. 543,122.22 restult fraction is .25 – JAVADEV Mar 28 '19 at 13:15
  • Sure, but that follows from your choice of using `float`s. They give you only 6-7 significant decimal digits (24 binary digits, to be exact). If you used `double`, which is the default FP format in Java, you'd have 15 significant digits. If that isn't enough, e.g. because you are calculating the federal budget of the USA, I concur with other posters and suggest you use `BigDecimal`. – Igor F. Mar 28 '19 at 13:35