How to format the decimal number precision like given below:
double d = 1/3 returns 0.3333333333333333 and mathematically 3 is repeated infinitely.
d = ((double)3)/ (double)41; returns 0.07317073170731707 and here 07317 is repeated.
Now, the ask to format the output like below
0.3333333333333333 should be formatted to 0.(3) as 3 is repeated.
Similarly 0.07317073170731707 should be formatted to 0.(07317) as 07317 repeated
I had looked into DecimalFormat class but I am able to format only number of precisions.
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("#0.'('##')'");
double d = ((double)1)/ (double)3;
System.out.println("formatted "+formatter.format(d));
System.out.println(d);
d = ((double)1)/ (double)2;
System.out.println("formatted "+formatter.format(d));
System.out.println(d);
d = ((double)3)/ (double)41;
System.out.println("formatted "+formatter.format(d));
System.out.println(d);
}
Output:
formatted 0.33()
0.3333333333333333
formatted 0.5()
0.5
formatted 0.07()
0.07317073170731707
Is there any built-in class in Java available to achieve the same?