Question

My question is :

How do I make the program print the number of digits before the decimal point and how many comes after a number.

public class Strings {
public static void main(String args[])
{
    double number = 17.0/3;

    DecimalFormat number_format = new DecimalFormat("#.###");
    System.out.println(number);
    String formatted_string = number_format.format(number);
    System.out.println(formatted_string);
     }
 }

I need the number of integers before decimal point

I need to get result of 1 and 3.

Was it helpful?

Solution

Number of digits before the decimal point - DecimalFormat#setMaximumIntegerDigits It does the job -

double number = (double)17/3;
java.text.DecimalFormat number_format = new java.text.DecimalFormat("#.###");
number_format.setMaximumIntegerDigits(0);
System.out.println(number);
String formatted_string = number_format.format(number);
System.out.println(formatted_string);

Result :

5.666666666666667
.667

OTHER TIPS

or a more simpler way

    double d = 17.0/3;
    System.out.format("%1.2f", d);

just try this

    double d = 15.0/4; // Assuming a number
    String ds = String.valueOf(d); // converting it into string (it will be 3.75)
    String arr[] = ds.split("\\D"); // splitting by non number charecter (in our case its dot)
    // So array containts ["3", "75"] strings
    System.out.println("Before Decimal point: "+ arr[0].length()); // length gives number of digits
    System.out.println("After Decimal point: "+ arr[1].length());

The easiest way to do this would be to convert the number to a string and then to split the string based on the '.' separator. Then split the first array element with "". The length of this array would give you your answer.

// number = some_number.some_more_numbers;
String value = number + ""; // convert to string
String[] parts = value.split(".");
String[] numbers = parts[0].split("");
int length = numbers.length; // Gives number of individual numbers before decimal point

I hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top