Scientifc Notation Java
-
01-03-2021 - |
Question
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());
}
}
}
Solution
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
OTHER TIPS
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^");
make your format string ".000" and it will not drop 'empty' zeroes from your formatted number.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow