-4

I am trying to write a java program that rounds to one decimal place less. For example if I have a total of 32.45678 it should be 32.4568 or if its 0 it should be 0.0. Here is what I have so far. Thanks

import java.text.DecimalFormat;
import java.util.Scanner;
public class product{

  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter the first number:");

    float f1 = scan.nextFloat();
    System.out.println("Enter the second number:");

    float f2 = scan.nextFloat();
    float p = f1*f2;

    DecimalFormat df = new DecimalFormat(".####");
    System.out.println("Product: "+df.format(p));

  }

} 
Tom
  • 16,842
  • 17
  • 45
  • 54
5ktm5
  • 1
  • 2

1 Answers1

0

The textual entered number 32.456 or 32.456432234 could become a float 32.45600004 or 32.456432. As floats and doubles are just approximations.

One could use BigDecimal as new BigDecimal("32.456") will have a precision (scale) of 3. The most satisfying solution IMO. So read the tokens as String.

One could read Strings, determine their precision, do a Float.parseFloat and format them to the decremented precision desired. A format for output would need to be made for that precision.

String s1 = scan.next();
BigDecimal f1 = new BigDecimal(s1);
int scale = f1.scale(); // 25E3 == 25000 with scale -3.
if (scale < 1) {
    scale = 1;
} else {
    --scale;
}
f1 = f1.setScale(scale, BigDecimal.ROUND_HALF_UP);

A suggestion more

Maybe you wanted just to round a bit more. (Doubting the last digit?)

float f1 = ...;
String s = Float.toString(f1);
if (s.contains("E")) {
    throw new IllegalStateException();
}
if (s.contains(".")) {
   s += ".0";
} else {
   char c = s.charAt(s.length() - 1);
   if (c >= '5') {
       char d = s.charAt(s.length() - 2);
       s = s.substring(0, s.length() - 2) + ((char) (d + 1));
   } else {
       s = s.substring(0, s.length() - 1);
   }
}
return s;
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Any more suggestions? – 5ktm5 Feb 02 '18 at 10:39
  • @5ktm5 depends on your needs, BigDecimal is a bit awkward, but good at financial software and such. Added a do-it-yourself rounding, either of any float, or a string as input. – Joop Eggen Feb 02 '18 at 11:00