Convert very small double values to string (with scientific notation) (Java) - java

I'm trying to print a small double number like 6.67e-11, but using Double.toString() returns 0. What can I do to make it print 6.67e-11 (or something similar) instead?

Unable to reproduce:
public class Test {
public static void main(String args[])
{
double d = 6.67e-11;
System.out.println(Double.toString(d)); // Prints "6.67E-11"
}
}
IIRC, Double.toString() always returns a string which allows the exact value to be round-tripped using Double.parseDouble().
My guess is that you don't actually have a small value - that you have 0, due to some rounding errors in other operations.

Related

Format method on String

When I am writing this code
float f=56.7876f;
System.out.print(String.format("%32.12f",f));
the output is: 56.787601470947
but, when I am writing this code
System.out.print(String.format("%32.12f",56.7876));
the output is: 56.787600000000
Why in both the cases different outputs are being printed despite of the fact that the functionality of both the code is same?
All floating point numbers without some suffix are double literals in Java. This is the reason why
float ohNoes = 56.7876;
will produce a compiler error (java: incompatible types: possible lossy conversion from double to float).
So If you write
public class Main {
public static void main(String... args) {
System.out.println(String.format("%32.12f",56.7876));
System.out.println(String.format("%32.12f",56.7876f));
}
}
You can see the diference. The first prints the double literal 56.7876, while the second prints the nearest float-representation of 56.7876.
The String.format( format, Object... args) eventually calls :
private void print(float value, Locale l) throws IOException {
print((double) value, l);
}
for float literals. See in Formatter$FormatSpecifier.java in Formatter.java
the value 56.787601470947 that you see is because the float literal 56.7876f is casted to a double as shown in above method.
If you print the following :
float f = 56.7876f;
System.out.println( (double)f );
you will see same value : 56.787601470947
System.out.print(String.format("%32.12f",56.7876)); It is returning 12 char fractional part filling with 0 and it consider 56.7876 as double.
you can refer following link:- https://dzone.com/articles/java-string-format-examples

Why won't String.format() give me a left zero-padded floating point output?

I'm trying to get the decimal 8.6 to render to a left zero-padded string i.e. 08.6.
Why doesn't the following seem to work?
double number = 8.6;
String.format("%03.1f", number); //expect "08.6", get "8.6"
The formatting string seems to be correct. What am I doing wrong?
It is giving you a left zero-padded floating point output, it's just that the field width of 3 includes the decimal point and the fractional portion (and the sign, if it's negative), so you need to use %04.1f instead for that particular value.
The output of:
public class Test {
public static void main(String[] args) {
double number = 8.6;
System.out.println(String.format("%04.1f", number));
}
}
is:
08.6
You need to give as %04.1f to get the output as 08.6.

How do I properly use the java.lang.Math?

I am in a COMP 110 class which is intro to Java. This specific program is irrelevant to the class but to help my own understanding with Java.
I believe I have imported the tool to allow the program to calculate basic math operations by using "java.lang.Math;"
I understand * is multiplication, / is division, + is addition, - is subtraction, and % finds the remainder.
The final line of the program gives me the error message:
squared.java:14: operator * cannot be applied to java.lang.String,java.lang.String
and I am at a loss for why because I have imported the language Math, which should enable me to use the * to multiply the value variable when I enter "value * value"
import java.util.Scanner;
import java.lang.Math;
public class squared {
public static void main(String[] args) {
Scanner number = new Scanner(System.in);
System.out.println("What number do you want to find the square of?");
String value = number.nextLine();
System.out.println("The square of the number" + value + "is" + value * value);
}
}
Yes you must first convert it into an Integer, Double, Float, etc in order to do a multiplication on such. So just do
int v = Integer.parseInt(value.trim());
Then
System.out.println("The square of the number"+v+"is"+ (v * v));
Also using operators has nothing to do with Math library. Math library is used like so:
double d = Double.parseDouble(value.trim());
Math.pow(d,2.0); //which does the same thing above
There are two approaches to go about this program -
1) Read the input as String and then convert it to int or
2) Read the input as int(or double?) itself.
Following code shows how you can read the input as int and perform the operation.
Note the code change (value*value) in your sysout statement. When you concatenate any value to a string, it get treated as string, and hence you are getting the error. Put it in parenthesis such that before concatenating, actual value*value operation is performed.
public class squared {
public static void main(String[] args){
Scanner number = new Scanner(System.in);
System.out.println("What number do you want to find the square of?");
int value = number.nextInt();
System.out.println("The square of the number"+value+"is"+ (value * value));
}
}
Talking about Math.pow(), it doesn't serve any different purpose here. Using it is same as the way you have done here.
First of all, you don't need to import java.lang.Math. All of the java.lang libraries are already there. Also, you don't need to use the Math library for operations. You use it for things like Math.sin() to find the sine of an angle, or Math.pow() to get the power of one number to another. If you want a full list of the uses for java.lang.Math, here is a link: http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
You probably want to store the input in a double, so rather than using number.nextLine(), you may want to use number.nextDouble(), and store it in a double, as below.
double value = number.nextDouble();
You were storing the value as a String, so the computer was reading the input as a quotation, like "cat," rather than the numbers. It doesn't work because what you were trying to do was akin to saying
"cat" * "dog."
Good luck in the class!

Compare first two decimal points

Suppose if I have 3.13 and 4.13, I want to be able to check whether .13 from 3.13 and .13 from 4.13.
I tried many things:
1) converting the two decimals to Strings and trying to split them up by ".", but I couldnt get that to work
2) a = 3.14;
a = a - Math.floor(a); to try to get the decimal alone but i end up getting 0.1400000001
converting the two decimals to Strings and trying to split them up by ".", but I couldnt get that to work
split uses a regex, so you have to escape the dot.
string.split(".")
should become
string.split("\\.")
With this you should be able to split the string properly and do your comparisons
By the way, i would use Reimenus solution, when you have numbers it's always better to use math if you can. Use strings only if you really need them.
You could separate the fractional part for comparison instead
double value1 = 3.13;
double value2 = 4.13;
double fractional1 = value1 - (long)value1;
double fractional2 = value2 - (long)value2;
System.out.println(Double.compare(fractional1, fractional2));
Read What Every Computer Scientist Should Know About Floating-Point Arithmetic too see
why you're seeing additional digits after your own numerical operation
your second method is actually correct. when comparing double values, you have to include a range.. Java: Double Value Comparison (refer this)
Try this out
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
float v1 = 3.13f,v2 = 4.13f;
//Converting float value into String array
String split1[]=Float.toString(v1).split("\\.");
String split2[]=Float.toString(v2).split("\\.");
//Comparing two strings
if(split1[1].equals(split2[1]))
{
System.out.println("Yes");
}
}
}

Convert Double to String value preserving every digit

How do I convert a double value with 10 digits for e.g 9.01236789E9 into a string 9012367890 without terminating any of its digits ?
I tried 9.01236789E9 * Math.pow(10,9) but the result is still double "9.01236789E18"
double d = 9.01236789E9;
System.out.println(BigDecimal.valueOf(d).toPlainString());
While 10 digits should be preservable with no problems, if you're interested in the actual digits used, you should probably be using BigDecimal instead.
If you really want to format a double without using scientific notation, you should be able to just use NumberFormat to do that or (as of Java 6) the simple string formatting APIs:
import java.text.*;
public class Test
{
public static void main(String[] args)
{
double value = 9.01236789E9;
String text = String.format("%.0f", value);
System.out.println(text); // 9012367890
NumberFormat format = NumberFormat.getNumberInstance();
format.setMaximumFractionDigits(0);
format.setGroupingUsed(false);
System.out.println(format.format(value)); // 9012367890
}
}
Try String.format("%20.0f", 9.01236789E9)
Note though it's never an exact value, so "preserving every digit" doesn't really make sense.
You can use it.
String doubleString = Double.toString(inValue)
inValue -----> Described by you.to what position you want to Change double to a string.
In this case, you can also do
double value = 9.01236789E9;
System.out.println((long) value); // prints 9012367890

Categories