Is there a way to get the number of places after the decimal point in dual Java?

I am working on a Java / Groovy program. I have a double variable that contains the number entered by the user. I really want to know how many digits the user entered to the right of the decimal point. Sort of:

double num = 3.14
num.getPlaces() == 2

Of course, you cannot do this with double, because using IEEE floating points, and it all comes close.

Assuming I cannot get the string entered by the user, but only has access to the double value stored in it, is there any way that I can clear this double, although BigDecimal or somesuch, to get the "real" number of decimal places? (When a double is displayed on the screen, it becomes right, so I guess there is a way, at least, to guess?)

+3
source share
7 answers

No, you cannot ... because there are many different lines that the user could enter, in which everyone would be parsed with the same value.

"" , . , 3.14 3.140000000000000124344978758017532527446746826171875. , .

, , :

3.14
3.140
3.140000
3.14000000000000012434

, , , .

, BigDecimal .

+14

, - , , , .

:

groovy:000> "123.0001".toBigDecimal()
===> 123.0001
groovy:000> "123.0001".toDouble()
===> 123.0001
groovy:000> new BigDecimal("123.0001".toDouble())
===> 123.000100000000003319655661471188068389892578125

, double, double BigDecimal. BigDecimal , , toString .

, . , , , , toString double, Decimal, , toString double, :

groovy:000> d = "123.0001".toDouble()
===> 123.0001
groovy:000> d.toString()
===> 123.0001
groovy:000> new BigDecimal(d.toString())
===> 123.0001

BigDecimal, , -

groovy:000> d = 123.0001
===> 123.0001
groovy:000> s = d.toString()
===> 123.0001
groovy:000> s.substring(s.indexOf('.')).length() - 1
===> 4

.

, - , groovy. ( , , , , , , , 0)

def getPlaces(d) {
    s = d.toString()
    s.substring(s.indexOf(".")).length() - 1
}
+3

, . , , . , ~ 12 .

:

  • BigDecimal . double .

  • .

  • BigDecimal.toString() "0" "9".

  • . , "1" . .

. .

, , decimal- > , , .

+2

, , , - . , String , , , - ?

static int getPlaces(double num) {
    String numString = String.valueOf(num);

    return numString.indexOf(".0")==numString.length()-2?0:numString.length()-numString.indexOf(".")-1;
}

 num.getPlaces() == 2

 getplaces(num) == 2

, .

, That the user entered. Good point.

, (, 5) , , , , - , , - / 5, 5.0. , 5 5.0.

+1

, . , - , , 1.99999999998 "2"

0

so if this is a user entered value. Take the value as a string. Then you can use string functions to find the position of ".". and then subtract this number from the string length to get the number you are looking for. Of course, you will want to trim () it and make sure that it is indeed the number that was entered.

0
source

Convert to BigDecimal. BigDecimal.scale () = number of places

0
source

Source: https://habr.com/ru/post/1724776/


All Articles