class Test{
public static void main(String Args[]){
Integer x;
x = Integer.decode("0b111");
System.out.println(x);
}
}
This doesn't work with the prefix 0 for binary and for octal with the prefix 0.
What is the correct way to do it?
Looking at the documentation for Integer.decode, I see no indication that binary should work. Octal should work though, with a prefix of just 0:
System.out.println(Integer.decode("010")); // Prints 8
You could handle a binary indicator of "0b" like this:
int value = text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
: Integer.decode(text);
Complete sample code showing binary, octal, decimal and hex representations of 15:
public class Test {
public static void main(String[] args) throws Exception {
String[] strings = { "0b1111", "017", "15", "0xf" };
for (String string : strings) {
System.out.println(decode(string)); // 15 every time
}
}
private static int decode(String text) {
return text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
: Integer.decode(text);
}
}
Integer.decode cannot parse binary, see API. But octal work fine, example:
int i = Integer.decode("011");
As of Java 7, you can use binary literals directly in your code. However, note that these are of type byte, short, int or long (and not String).
int x = 0b111;
Related
I am trying to figure out how to show the correct number of digits after a decimal, based off a number passed into the method.
public static double chopDecimal(double value, int place)
{
int chopped;
//???
return chopped;
}
So if the value passed is 123.456789 and the place is 2, it should show 123.45.
The print statement is in another method.
System.out.println("***MyMath ChopDecimal Test***");
//Chop Decimal Test 1
if (MyMath.chopDecimal(123.456789, 2) == 123.45)
{
System.out.println("Chop Decimal Test 1 Passed");
}
else
{
System.out.printf("Chop Decimal Test 1 Failed. Your answer: %f Correct Answer: 123.45\n",
MyMath.chopDecimal(123.456789, 2));
}
//Chop Decimal Test 2
if (MyMath.chopDecimal(.98765, 4) == .9876)
{
System.out.println("Chop Decimal Test 2 Passed");
}
else
{
System.out.printf("Chop Decimal Test 2 Failed. Your answer: %f Correct Answer: .9876\n",
MyMath.chopDecimal(.98765, 4));
}
This is possible using java.text.NumberFormat, although when you wish to convert to String for 'showing' purposes.
To match your example though, I've converted it babck to a double:
public static double chopDecimal(double value, int place)
{
String chopped = NumberFormat.getInstance().setMaximumFractionDigits( place ).format( value );
return Double.valueOf( chopped );
}
I suggest you to use the java Rounding Mode.
Simple example:
public static void main(String[] args) {
System.out.println(chopDecimal(123.456789, 2));
}
public static String chopDecimal(double value, int place)
{
// Parameter is the pattern
DecimalFormat format = new DecimalFormat("0.00");
format.setRoundingMode(RoundingMode.HALF_UP);
return format.format(value);
}
This question is duplicated:
How to round a number to n decimal places in Java
Reference:
Oracle Documentation
All of the answers above are pretty great, but if this for something you need to be able to explain, I wrote the segment of code below with all pretty basic tools of programming. Study this process below, it's not always about the solution, more so about can you come up with a solution. Always keep that in mind when solving any problem. There is always time later to improve your solution.
public static void main(String[] args) {
chopDecimal(123.456789,2);
}
public static double chopDecimal(double value, int place)
{
String valToStr = Double.toString(value);
int decimal=0;
for(int i = 0; i < valToStr.length(); i++)
{
if(valToStr.charAt(i) == '.')
{
decimal = valToStr.indexOf(valToStr.charAt(i));
System.out.println(decimal);
break;
}
}
String newNum = valToStr.substring(0,(++decimal+place));
System.out.println(newNum);
double chopped = Double.parseDouble(newNum);
return chopped;
}
}
Let me know if you have any questions.
You can use BigDecimal and setScale:
double chopped = BigDecimal
.valueOf(value)
.setScale(place, RoundingMode.DOWN)
.doubleValue()
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
This question already has answers here:
Java Integer parseInt error
(4 answers)
Closed 6 years ago.
I need to convert the string of hex to decimal in java..
My hex value is "00000156A56BE980".
My required output is 1471654128000
I have done the following in java,
public static void main (String args [])
{
String hexValue = " 00000156A56BE980 ";
Integer result = Integer.parseInt(hexValue, 16);
System.out.println(result);
}
but I am getting the following error,
Number format Exception for input string "00000156A56BE980"
I have tried by giving long also the same error coming.. For other hex value it's coming but when we give hex string of larger value it shows the error.
How can we convert this number to decimal?
Can anyone solve this issue for me?
Try it like so
import java.math.*;
class Main {
public static void main (String args [])
{
String hexValue = "00000156A56BE980";
BigInteger result = new BigInteger(hexValue, 16);
System.out.println(result);
}
}
See also this repl.it
The problem is probably because your value does not fit within the value range (-231 to 232-1) of Integer - see the docs
The number is too large for a 32-bit int
Try using a long instead.
public static void main(String[] args) {
String hexValue = "00000156A56BE980";
long result = Long.parseLong(hexValue, 16);
System.out.println(result);
}
Note: you can't have spaces in a number. You can call .trim() to remove them.
2 thing in order the code can work:
remove spaces trimming the String
the result doenst fit in an integer so use either Long or BigInteger instead
public static void main(String[] args) {
String hexValue = " 00000156A56BE980 ";
long result = Long.parseLong(hexValue.trim(), 16);
System.out.println(result);
}
The number is too big for integer (> 2^32).
(The value represented by the string is not a value of type int.)
Take a look here
I know I could use String.substring or write some extra code, but is there a simple way to achieve this by only using String.format?
For example, I only want the first 6 chars "1234ab" in the result:
int v = 0x1234abcd;
String s = String.format("%06x", v) // gives me 1234abcd
String s = String.format("%06.6x", v) // gives me IllegalformatPrecesionException
The Java Formatter doc said the precision could be used to limit the overall output width, but only to certain data types.
Any ideas? Thanks.
Depending how may hex digits you want to truncate...
You can divide by powers of 16
public static void main(String[] args) throws Exception {
int v = 0x1234abcd;
// This will truncate the 2 right most hex digits
String hexV = Integer.toHexString(v / (int)Math.pow(16, 2));
System.out.println(hexV);
}
Results:
1234ab
Even if you mess up and divide by a power of 16 that exceeds the length of your hex string, the result will just be zero.
Then there's the substring() approach
public static void main(String[] args) throws Exception {
int v = 0x1234abcd;
String hexV = Integer.toHexString(v);
// This will truncate the the 2 most right hex digits
// provided the length is greater than 2
System.out.println(hexV.length() > 2 ? hexV.substring(0, hexV.length() - 2) : hexV);
}
Since you wanted to do this with just the Formatter.
Here's my result.
1234ab
1234abcd
And here's the code.
public class Tester {
public static void main(String[] args) {
int v = 0x1234abcd;
String s = String.format("%6.6s", String.format("%x", v));
System.out.println(s);
s = String.format("%10.10s", String.format("%x", v));
System.out.println(s);
}
}
I convert the hex number to a String, then truncate or left pad the String with the second Formatter.
how can we convert hexadecimal number string to double-precision number in java ?
in matlab it's simple :
>> hex2num('c0399999a0000000')
ans =
-25.6000
but could I do the same things in java also ?
I tried parseInt() but this number is not integer.
I think you want Double.longBitsToDouble, like this:
public class Test {
public static void main(String[] args) {
String hex = "c0399999a0000000";
long longHex = parseUnsignedHex(hex);
double d = Double.longBitsToDouble(longHex);
System.out.println(d);
}
public static long parseUnsignedHex(String text) {
if (text.length() == 16) {
return (parseUnsignedHex(text.substring(0, 1)) << 60)
| parseUnsignedHex(text.substring(1));
}
return Long.parseLong(text, 16);
}
}
(The fact that long is signed in Java makes this more awkward than you'd really want, but hey...)
First make a long, and then call longBitsToDouble