0

I have a user string generated by some computations. The user string is "3.2E7" It is written in Scientific Notation. I need to convert it to standard notation because the drawing instructions on the App overlap if it reads a Scientific Notation number.

I do know how to convert it to Standard Notation use the Number class, as the following shows:

String generated = "3.2E7"
try{
  NumberFormat format = NumberFormat.getInstance();
  Number my_number = format.parse(generated);
  System.out.println("see my number: " + my_number); //this prints correctly: 32000000


 }catch(Exception exception){
   Log.d("see009",""+exception);
  }

Now, the problem I am having is that if the variable 'generated' < 1 but greater than zero. Then, the NumberFormat class does not convert it properly:

String generated = "3.2E-7";
//inside the try catch block from above:
System.out.println("see my number: " + my_number); //this prints 3.2E-7  NOT: 0.00000032

Doesn't the Number class accept non-integers. How can I make the NumberFormat object format the Scientific notation number less than 1?

i_o
  • 777
  • 9
  • 25

1 Answers1

0

Working with the BigDecimal class I have been able to overcome the problem:

Simply do this:

String generated = "3.2E7";
BigDecimal big_decimal = new BigDecimal(generated);
System.out.println("look at this: " + big_decimal.toPlainString()); //will print: 32000000

generated = "3.2E-7";
big_decimal = new BigDecimal(generated);
System.out.println("look at this: " + big_decimal.toPlainString()); //will print: 0.00000032

BigDecimal even worked with powers in the magnitude of 20. It is a very efficient solution that is good for my needs.

i_o
  • 777
  • 9
  • 25
  • since you found the correct solution, just a side note: If I run your first attempt, I got printed "see my number: 3.2E-6" due to rounding errors. This might be worse than the improperformatting, since it is way more error prone. – juwil Jan 17 '21 at 19:11
  • So you are saying that BigDecimal is not able to turn 3.2E-6 into Standard Form? @juwil – i_o Jan 17 '21 at 19:36
  • no, you are absolutely right with your solution. The wrong result 3.2E-6 I got with the way you used in your question and that alone should be reason enough to prefer the solution you posted in your answer. – juwil Jan 17 '21 at 19:40
  • @juwil yes I know. I never knew BigDecimal was such an easy fix. I think I will start using it for computations instead of Double or Float. But, I think that BigDecimal is not as precise as Double or Float! – i_o Jan 17 '21 at 19:43
  • BigDecimal is as precise as you want, provided you set the precision (see https://stackoverflow.com/questions/9482889/set-specific-precision-of-a-bigdecimal). Float and double are not precise, but operations are way faster and efficient. So which to use depends on your requirements. – juwil Jan 17 '21 at 20:36