-1

I could not find answer for my question on the net, so that's why I'm here.

I want to print a number with specified number of digits example in java:

Length = 10

1.123456789      ==> 1.123456789

123.123456789    ==> 123.1234567

123456.123456789 ==> 123456.1234
Nurjan
  • 5,184
  • 5
  • 30
  • 47

4 Answers4

2

It seems you need to fetch the first n digits from the String representation of the number. However, the decimal separator should not be counted as a digit:

String printNumber(double number, int n) {
   String value = String.valueOf(number);
   String result = "";
   int count = 0;
   for (char c : value.toCharArray()) {
       if (count == n) break;
       if (c != '.') {
           count++;
       }
       result += c;
   }
   return result;
}
Konstantin Yovkov
  • 59,030
  • 8
  • 92
  • 140
1

You can try this:

Double number = 1.123456789;
BigDecimal bigDecimal = new BigDecimal(number).setScale(6, RoundingMode.HALF_EVEN);
System.out.println("double value: " + bigDecimal.doubleValue());

In the setScale method you can choose number of digits after dot.

Nurjan
  • 5,184
  • 5
  • 30
  • 47
0

Well, you can calculate the amount based on the length of the non-decimal number:

public String doubleToString(double in) {
    int length = (((int) in) + "").length(); //non-decimal length
    if (length <= 0 || length > 10) {
        //error out? not sure how you wish to handle 11-digit numbers
    }
    return String.format("%." + (10 - length) + "f", in); //format decimal
}

Shortened:

//default to 0 decimals for >10 digits
public String doubleToString(double in) {
    return String.format("%." + Math.max(0, (10 - (((int) in) + "").length()) + "f", in);
}
Rogue
  • 9,871
  • 4
  • 37
  • 66
0

save the number as string and take the substring from 0 to 10. now you can parse it back and got the number with 10 digits

Aelop
  • 156
  • 9