2

I am working on a problem which was given to me by my friend. I need to take the input number in the form x.yzw*10^p where p is non zero and x.yzw can be zeros. I have made the program but the problem is that when we have numbers such as 0.098, decimal format will make it 9.8 but I need to get it to be 9.800, it has to always be outputted as x.yzw*10^p. can someone please show me how this is possible.

input:    output:
1234.56   1.235 x 10^3
1.2       1.200
0.098     9.800 x 10^-2

Code:

 import java.util.Scanner;
    import java.math.RoundingMode;
    import java.text.DecimalFormat;

public class ConvertScientificNotation {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        DecimalFormat df = new DecimalFormat("0.###E0");
        double input = sc.nextDouble();
        StringBuffer sBuffer = new StringBuffer(Double.toString(input));

        sBuffer.append("00");
        System.out.println(sBuffer.toString());
        StringBuffer sb = new StringBuffer(df.format(Double.parseDouble(sBuffer.toString())));

        if (sb.charAt(sb.length()-1) == '0') {
            System.out.println(sBuffer.toString());
        } else {
            sb.replace(sb.indexOf("E"), sb.indexOf("E")+1, "10^");
            sb.insert(sb.indexOf("10"), " x ");
            System.out.println(sb.toString());
        }
    }
}
Kailua Bum
  • 1,368
  • 7
  • 25
  • 40
Jeel Shah
  • 3,274
  • 17
  • 47
  • 68
  • I would suggest starting by looking at [DecimalFormat](http://download.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html); it should do most of what you're looking for relatively easily. – Mike Nov 15 '11 at 14:29

3 Answers3

2
DecimalFormat myFormatter = new DecimalFormat(".000");
String output = myFormatter.format(input)

then if you want to convert 'output' into a number, use:

Float answer = Float.parseFloat(output)

EDIT

also check this out, it contains more information on how to format numbers

PTBG
  • 585
  • 2
  • 20
  • 46
1
DecimalFormat df = new DecimalFormat("0.###E0");
df.setMinimumFractionDigits(3);
df.setMaximumFractionDigits(3);

String formatted = df.format(0.098); //"9.8E-2"

Then you can just do a search and replace for E:

String replaced = formatted.replaceAll("E", " x 10^");
Mark Peters
  • 80,126
  • 17
  • 159
  • 190
0

make your format string ".000" and it will not drop 'empty' zeroes from your formatted number.

mcfinnigan
  • 11,442
  • 35
  • 28