Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first non-zero digit of a BigDecimal

In java how do I get the first non-zero digit of a BigDecimal?

For example:

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

For numbers between 0 and 1 this will work:

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

For numbers bigger than 1 this will work:

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

But is there a solution, that works for any number?

like image 562
slartidan Avatar asked Sep 29 '15 15:09

slartidan


People also ask

How do you find the whole number in BigDecimal?

intValue() is an in-built function which converts this BigDecimal to an integer value. This function discards any fractional part of this BigDecimal. If the result of the conversion is too big to be represented as an integer value, the function returns only the lower-order 32 bits.

How do you check BigDecimal precision?

BigDecimal. precision() method returns the precision of this BigDecimal. The precision is the number of digits in the unscaled value.

What is scale and precision in BigDecimal?

A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.

Which is more accurate BigDecimal or double?

A BigDecimal is an exact way of representing numbers. A Double has a certain precision. Working with doubles of various magnitudes (say d1=1000.0 and d2=0.001 ) could result in the 0.001 being dropped alltogether when summing as the difference in magnitude is so large. With BigDecimal this would not happen.


1 Answers

Here's a solution using just 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
like image 84
João Neves Avatar answered Oct 11 '22 10:10

João Neves