Toni Joe
Toni Joe

Reputation: 8417

how to display scientific notation to power of 10 in java?

Is there any way to i can display large numbers in powers of "10" instead of "E" like this:

1x10²

instead of:

1.0E2

Thanks

Upvotes: 1

Views: 1900

Answers (2)

KeV
KeV

Reputation: 2891

If performance doesn't matter you could write your own procedure to do the conversion.

public String toScientific(String input) {
    String result = "";
    int indexOfE = input.indexOf("E");

    result = input.substring(0, indexOfE); // Get first part (e.g. "1.0")
    result += " x 10^"; // Add "x 10^" --> "1.0 x 10^"
    result += input.substring(indexOfE + 1, input.length()); // Add exponent

    return result;
}

Input : "1.0E2" , Output : "1.0 x 10^2"

Upvotes: 3

Raghav Malik
Raghav Malik

Reputation: 840

There is in fact a way to print out superscript characters. Unicode allows you to print any digit from 0 to 9 as a superscript (2070 to 2079, see http://unicode.org/charts/PDF/U2070.pdf)

From there it is a matter of reading your input number and some string formatting to determine which Unicode characters need to be printed. Unfortunately I don't think there is a prebuilt library in java which does this for you. Let me know if you need sample code and I can provide it.

EDIT: This is good for the console. If you need to put it into a GUI component, JLabel can accept HTML so you can say new JLabel("<html>1x10<sup>2</sup></html>"); to display that in a form.

Upvotes: 2

Related Questions