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
Related
import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(s, s.charAt(0)); // ERROR!
}
}
I want to parse the input string based on char position to get the positional integer.
Error message:
Exception in thread "main" java.lang.NumberFormatException: radix 49 greater than Character.MAX_RADIX
at java.lang.Integer.parseInt(Unknown Source)
at test.main(test.java:11)
That method you are calling parseInt(String, int) expects a radix; something that denotes the "number system" you want to work in, like
parseInt("10", 10)
(10 for decimal)! Instead, use
Integer.parseInt(i)
or
Integer.parseInt(i, 10)
assuming you want to work in the decimal system. And to explain your error message - lets have a look at what your code is actually doing. In essence, it calls:
Integer.parseInt("123", '1')
and that boils down to a call
Integer.parseInt("123", 49) // '1' --> int --> 49!
And there we go - as it nicely lines up with your error message; as 49 isn't a valid radix for parsing numbers.
But the real answer here: don't just blindly use some library method. Study its documentation, so you understand what it is doing; and what the parameters you are passing to it actually mean.
Thus, turn here and read what parseInt(String, int) is about!
Integer.parseInt(parameter) expects the parameter to be a String.
You could try Integer.parseInt(s.charAt(0) + ""). The +"" is to append the character to an empty String thereby casting the char to String and this is exactly what the method expects.
Another method to parse Characters to Integers (and in my opinion much better!) is to use Character.getNumericValue(s.charAt(0));
Check this post for further details on converting char to int
Need to convert String.valueOf(s.charAt(0)) to String.valueOf(s.charAt(0)) i.e. Char to String.
import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(String.valueOf(s.charAt(0)));
}
}
Let use what we have here.
To parse one digit from a String into an integer. Use getNumericValue(char)
In your case, to get the first character into a number :
int n = Character.getNumericValue(s.charAt(0));
Be aware that you should take the absolute value if you integer can be negative.
Please comment me freely. What was wrong in the following program. It is giving different round result.
public class Test {
public static String round(double value, int places) {
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.toPlainString();
}
public static void main(String[] args) throws Exception {
double value1 = 1.1234565;
System.out.println(round(value1, 6));
double value2 = 1.1235;
System.out.println(round(value2, 3));
}
}
Why it is out put like that?
1.123457
1.123 --> Actually, I expect 1.124
In Doc(eclipse)
You're calling the BigDecimal(double) constructor. That's documented as:
Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value. The scale of the returned BigDecimal is the smallest value such that (10scale × val) is an integer.
The notes are illuminating too, and I suggest you read them.
The value you're passing in is exactly 1.12349999999999994315658113919198513031005859375, as that's the closest double to 1.1235. You can see that if you print out bd.toPlainString() before calling setScale. Therefore, that isn't half-way between 1.123 and 1.124 - it's closest to 1.123.
If you want a BigDecimal value of exactly 1.1235, I suggest you pass it as a String instead:
import java.math.*;
public class Test {
public static String round(String value, int places) {
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.toPlainString();
}
public static void main(String[] args) throws Exception {
String value1 = "1.1234565";
System.out.println(round(value1, 6));
String value2 = "1.1235";
System.out.println(round(value2, 3));
}
}
Alternatively you could use BigDecimal.valueOf(double) instead of new BigDecimal(double) - but then you still have the problem that you've converted your real original source data (the text in your source code) into a binary floating point number first, potentially losing information.
The problem is you are using to exact represention of the double including any representation error. A simple solution is to use the value you would get from the double if it was printed.
public static String round(double value, int places) {
return BigDecimal.valueOf(value)
.setScale(places, RoundingMode.HALF_UP);
.toPlainString();
}
BigDecimal.valueOf uses the simplest value which would be represented as the double you have.
I've an exponential string value
String str = "2.00000181334612E15";
And I'm trying to convert it to a double value.
Double d = (Double.parseDouble(str));
But am getting an Exception as follows,
Exception in thread "main" java.lang.NullPointerException
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1047)
at java.lang.Double.parseDouble(Double.java:521)
at com.swissre.lhrte.poi.test.TestClient.main(Test.java:133)
What am I doing wrong?
There is no problem in your code. To see this, consider this code segment:
public class exp {
public static void main(String[] args) {
String str = "2.00000181334612E15";
Double d = (Double.parseDouble(str));
System.out.println(d);
}
};
If you are getting a NullPointerException from Double.parseDouble then it means that you gave it a null argument. The code lines in your answer don't give it a null argument. So I guess in your full code you must be giving Double.parseDouble a null argument without you realizing it.
According to the Double.parseDouble() documentation, it calls Double.valueOf() and the documentation of Double.valueOf() specifies that you may give it exponential values.
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.
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.