How to get the first nonzero digit of BigDecimal

In java, how do I get the first nonzero digit of BigDecimal?

For instance:

0.001 => 1 0.02 => 2 987.654 => 9 

For numbers from 0 to 1, this will work:

 bigDecimal.scaleByPowerOfTen(bigDecimal.precision()).setScale(0, RoundingMode.DOWN) 

For numbers greater than 1, this will work:

 bigDecimal.scaleByPowerOfTen(1-bigDecimal.precision()).setScale(0, RoundingMode.DOWN) 

But is there a solution that works for any number?

+5
source share
2 answers

Here's a solution using only BigDecimal and int :

 BigDecimal value = new BigDecimal(0.021); //input your value here int scale = value.scale(); int precision = value.precision(); int result = value.movePointLeft(precision-scale-1).abs().intValue(); //this will generate the result you need 
+4
source

You can convert BigDecimal to char[] and check the numbers using a loop. See the following example.

  BigDecimal bigDecimal = new BigDecimal(5220.33); char[] chars = String.valueOf(bigDecimal).toCharArray(); for (char c : chars) { if (Character.isDigit(c) ? Character.getNumericValue(c) != 0 : false) { System.out.println("First number is : " + c); return; } } 
+2
source

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


All Articles