Number of decimal digits in a double [closed]

2020-01-25 00:34发布

How do I determine number of integer digits and the number of digits after decimal in a number like 234.12413 in Java.

标签: java double
4条回答
在下西门庆
2楼-- · 2020-01-25 00:48
    String s = "" + 234.12413;
    String[] result = s.split("\\.");
    System.out.println(result[0].length() + " " + result[1].length());
查看更多
成全新的幸福
3楼-- · 2020-01-25 00:52

1) convert to string

2) substring from '.' to end

3) get the length of this substring

查看更多
甜甜的少女心
4楼-- · 2020-01-25 00:56
Double d = 234.12413;
String[] splitter = d.toString().split("\\.");
splitter[0].length();   // Before Decimal Count
splitter[1].length();   // After  Decimal Count
查看更多
何必那么认真
5楼-- · 2020-01-25 00:59

A double is not always an exact representation. You can only say how many decimal places you would have if you converted it to a String.

double d= 234.12413;
String text = Double.toString(Math.abs(d));
int integerPlaces = text.indexOf('.');
int decimalPlaces = text.length() - integerPlaces - 1;

This will only work for numbers which are not turned into exponent notation. You might consider 1.0 to have one or no decimal places.

查看更多
登录 后发表回答