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?
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.
BigDecimal. precision() method returns the precision of this BigDecimal. The precision is the number of digits in the unscaled value.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With