Search code examples
javadecimalnotationexponential

How to print a large number with exponential notation?


If I have a number 52000000000, and I want to print it out as 5.2E+9, how do I do that with printf?


Solution

  • Since it's a simple method I'll guide you through it.

    You'll need two counters: one for the number itself (type double, let's call it 'num'), and one for the exponent (integer, let's call it exp). You'll need a while loop such that while num is greater than 10, divide num by 10 and increase exp by 1. So, something like 7600 should have num = 7.6, exp = 3.

    Depending on your return type, you can return these values in numerous ways. A simple way would be to have return type string and return num+"E"+exp.