0

I have the following problem: I have big values stored in the String, and I can only display number that is 7 digit long. Here are the examples after converting from string to float - I have String 300 which should be 300, but it is 300.0 Everything that's bigger than 7 digits should be written in scientific notation (700000000 should be 7E+8) It also could be 7.0E8, but I prefer 7E+8.

I have tried formatting the string but when I wasn't able to get rid of .0 without getting rid of scientific notation. Is this even possible ?

Robert Vangor
  • 1,018
  • 1
  • 13
  • 24
  • 1
    Please post what you have tried, StackOverflow is to help you out not to implement things for you. this is a pretty simple implementation – Will Evers Sep 08 '16 at 17:14
  • This is a similar question that may help http://stackoverflow.com/questions/703396/how-to-nicely-format-floating-numbers-to-string-without-unnecessary-decimal-0 – LeHill Sep 08 '16 at 17:36

2 Answers2

0

The class DecimalFormat from the package java.text handles this almost effortlessly. A tad bit of business logic for your specific case seals the deal.

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class NumberFormatter
{
  public static void main(String args[])
  {
    String stringInput = "1234.5678";
    String outputString = null;
    if (stringInput.length() < 8)
    {
      outputString = stringInput;
    }
    else
    {
      outputString = scientificOutput(stringInput);
    }
    System.out.println(outputString);
  }

  private String scientificOutput(String input)
  {
    NumberFormat formatter = new DecimalFormat("0.###E0");
    Double d = Double.parseDouble(input);
    if (d % 1 == 0)
    {
      // is int
      return formatter.format(d.intValue());
    }
    else
    {
      // is a double
      return formatter.format(d); 
    }
  }
}
JynXXedRabbitFoot
  • 996
  • 1
  • 7
  • 17
0

Try this:

String inputValue = "700000000";
String result;

DecimalFormat df1 = new DecimalFormat("@######");
df1.setMinimumFractionDigits(0);
DecimalFormat df2 = new DecimalFormat("@#####E0");
df2.setMinimumFractionDigits(1);

if (inputValue.length() <= 7) {
    result = df1.format(Double.parseDouble(inputValue));
} else {
    result = df2.format(Double.parseDouble(inputValue));
}
dzikovskyy
  • 5,027
  • 3
  • 32
  • 43