Convert string to int with 1st null saving - java

Usually Integer.valueOf(), Integer.parseInt() works perfect. But i have problem if in a String object are some nulls(0), here is some code.
StringBuilder sb = new StringBuilder();
sb.append("0");
sb.append(9);
Integer afterConvert = Integer.valueOf(sb.toString());
System.out.println(afterConvert);
This code shows "9", but i need "09". Is any way to achieve it?

This has nothing to do with null values.
The Integer value of 09 is 9.
If you want to print leasing zeros, use:
System.out.println(String.format("%02d", afterConvert));
See similar question here.

You cannot print Integer with leading 0s like this. You can use NumberFormat class:
NumberFormat nb = NumberFormat.getInstance();
nb.setMinimumFractionDigits(2);
System.out.println(nb.format(afterConvert));

Related

Java Object format to String Number with Decimals

so I have an array list of Objects and in it are string numbers. I want to add decimal places to these numbers (8).
String value = String.valueOf(accountEntry.get(4));
double amount = Double.valueOf(value);
String formatted = String.format(Locale.GERMANY,"%.8f",amount);
accountEntry.add(formatted);
For example 101700000000 should output 1017 but instead it is 101700000000,00000000
Does anyone know where the problem is?
Hello try something like this using Regex , this way you can remove all zeros at the end.
String value = String.valueOf("101700000000");
double amount = Double.valueOf(value);
String formatted = String.format(Locale.GERMANY,"%d",(long)amount);
formatted = formatted.replaceAll("0+$", "");
System.out.println(formatted);
Input :101700000000 ===> Output: 1017
Does anyone know where the problem is?
Your Input is : 101700000000 and you are formatting String.format(Locale.GERMANY,"%.8f",amount); In here your output will be 101700000000,00000000 So for understand this String Format will not transform your input magicaly to 1017. You need to use another algorithm for this problem

Remove decimals after a numeric value in java

Hi I have a excel file reading application which reads every cell in the file.
whenever a cell contains a numeric value the app is treating it a numeric cell.
For example the cell contains (40002547) the application will treat this as numeric cell. I cab get the value by using this code:
SONum = String.valueOf(cellSONum.getNumericCellValue());
Well that works fine. My Problem is it appends decimal at the end of the string. it will be (40002547.0). I need it to be as is. Thanks in advance
It's because cellSONum.getNumericCellValue() is returning a floating point type. If you force it to an integer before calling valueOf(), you should get the string representation in an integral form, if indeed that's what you want for all possibilities:
SONum = String.valueOf((int)cellSONum.getNumericCellValue());
You can see this in the following code:
class Test {
public static void main(String[]args) {
double d = 1234;
System.out.println(String.valueOf(d));
System.out.println(String.valueOf((int)d));
}
}
which outputs:
1234.0
1234
However, if you want to just get rid of .0 at the end of any string but allow non-integral values to survive, you can just remove the trailing text yourself:
class Test {
public static void main(String[]args) {
double d1 = 1234;
double d2 = 1234.567;
System.out.println(String.valueOf(d1).replaceFirst("\\.0+$", ""));
System.out.println(String.valueOf(d2).replaceFirst("\\.0+$", ""));
}
}
That snippet outputs:
1234
1234.567
Try with split().
SONum = String.valueOf(cellSONum.getNumericCellValue());
SONum = SONum.split("\\.")[0];
When you split 40002547.0 with . ,the split function returns two parts and the first one you need.
If you want to be sure you are not cutting of any valid decimals, you can use regexp also:
String pattern = "\.0+"; // dot followed by any number of zeros
System.out.println(String.valueOf(cellSONum.getNumericCellValue()).replaceAll(pattern, ""));
More on java regexp for example: http://www.vogella.com/articles/JavaRegularExpressions/article.html
As PaxDiablo also mentions, cellSONum.getNumericCellValue() returns a floating point.
You can cast this to Long or int to get rid of all behind the '.'
String SONum = String.valueOf(cellSONum.getNumericCellValue().longValue());
used as example:
String SONum = String.valueOf((new Double(0.5)).longValue());
SONum = ""+cellSONum.getNumericCellValue().split(".")[0];
try
double value = 23.0;
DecimalFormat df = new DecimalFormat("0.##");
System.out.println("bd value::"+ df.format(value))
Consider using BigDecimal.
You could simply say
BigDecimal scaledDecimal = new BigDecimal(value).setScale(0, RoundingMode.HALF_EVEN);
This will help in case your input is String and you need result also in String
1). Convert the string to Double using Double.parseDouble,
2). Type cast to int, then convert to string using String.valueOf()
private String formatText(String text) {
try {
return String.valueOf((int) Double.parseDouble(text));
} catch (NumberFormatException e) {
return text;
}
}
You can do Explicit type casting to remove the decimals,
double desvalue = 3.586;
int value = (int)desvalue;

java convert to int

I am trying to convert to int like this, but I am getting an exception.
String strHexNumber = "0x1";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
Exception in thread "main" java.lang.NumberFormatException: For input string: "0x1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
It would be a great help if someone can fix it.
Thanks.
That's because the 0x prefix is not allowed. It's only a Java language thing.
String strHexNumber = "F777";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
System.out.println(decimalNumber);
If you want to parse strings with leading 0x then use the .decode methods available on Integer, Long etc.
int value = Integer.decode("0x12AF");
System.out.println(value);
Sure - you need to get rid of the "0x" part if you want to use parseInt:
int parsed = Integer.parseInt("100", 16);
System.out.println(parsed); // 256
If you know your value will start with "0x" you can just use:
String prefixStripped = hexNumber.substring(2);
Otherwise, just test for it:
number = number.startsWith("0x") ? number.substring(2) : number;
Note that you should think about how negative numbers will be represented too.
EDIT: Adam's solution using decode will certainly work, but if you already know the radix then IMO it's clearer to state it explicitly than to have it inferred - particularly if it would surprise people for "035" to be treated as octal, for example. Each method is appropriate at different times, of course, so it's worth knowing about both. Pick whichever one handles your particular situation most cleanly and clearly.
Integer.parseInt can only parse strings that are formatted to look just like an int. So you can parse "0" or "12343" or "-56" but not "0x1".
You need to strip off the 0x from the front of the string before you ask the Integer class to parse it. The parseInt method expects the string passed in to be only numbers/letters of the specified radix.
try using this code here:-
import java.io.*;
import java.lang.*;
public class HexaToInteger{
public static void main(String[] args) throws IOException{
BufferedReader read =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the hexadecimal value:!");
String s = read.readLine();
int i = Integer.valueOf(s, 16).intValue();
System.out.println("Integer:=" + i);
}
}
Yeah, Integer is still expecting some kind of String of numbers. that x is really going to mess things up.
Depending on the size of the hex, you may need to use a BigInteger (you can probably skip the "L" check and trim in yours ;-) ):
// Convert HEX to decimal
if (category.startsWith("0X") && category.endsWith("L")) {
category = new BigInteger(category.substring(2, category.length() - 1), 16).toString();
} else if (category.startsWith("0X")) {
category = new BigInteger(category.substring(2, category.length()), 16).toString();
}

How to convert BigInteger to String in java

I converted a String to BigInteger as follows:
Scanner sc=new Scanner(System.in);
System.out.println("enter the message");
String msg=sc.next();
byte[] bytemsg=msg.getBytes();
BigInteger m=new BigInteger(bytemsg);
Now I want my string back. I'm using m.toString() but that's giving me the desired result.
Why? Where is the bug and what can I do about it?
You want to use BigInteger.toByteArray()
String msg = "Hello there!";
BigInteger bi = new BigInteger(msg.getBytes());
System.out.println(new String(bi.toByteArray())); // prints "Hello there!"
The way I understand it is that you're doing the following transformations:
String -----------------> byte[] ------------------> BigInteger
String.getBytes() BigInteger(byte[])
And you want the reverse:
BigInteger ------------------------> byte[] ------------------> String
BigInteger.toByteArray() String(byte[])
Note that you probably want to use overloads of String.getBytes() and String(byte[]) that specifies an explicit encoding, otherwise you may run into encoding issues.
Use m.toString() or String.valueOf(m). String.valueOf uses toString() but is null safe.
Why don't you use the BigInteger(String) constructor ? That way, round-tripping via toString() should work fine.
(note also that your conversion to bytes doesn't explicitly specify a character-encoding and is platform-dependent - that could be source of grief further down the line)
You can also use Java's implicit conversion:
BigInteger m = new BigInteger(bytemsg);
String mStr = "" + m; // mStr now contains string representation of m.
When constructing a BigInteger with a string, the string must be formatted as a decimal number. You cannot use letters, unless you specify a radix in the second argument, you can specify up to 36 in the radix. 36 will give you alphanumeric characters only [0-9,a-z], so if you use this, you will have no formatting. You can create: new BigInteger("ihavenospaces", 36)
Then to convert back, use a .toString(36)
BUT TO KEEP FORMATTING:
Use the byte[] method that a couple people mentioned. That will pack the data with formatting into the smallest size, and allow you to keep track of number of bytes easily
That should be perfect for an RSA public key crypto system example program, assuming you keep the number of bytes in the message smaller than the number of bytes of PQ
(I realize this thread is old)
To reverse
byte[] bytemsg=msg.getBytes();
you can use
String text = new String(bytemsg);
using a BigInteger just complicates things, in fact it not clear why you want a byte[]. What are planing to do with the BigInteger or byte[]? What is the point?
String input = "0101";
BigInteger x = new BigInteger ( input , 2 );
String output = x.toString(2);
//How to solve BigDecimal & BigInteger and return a String.
BigDecimal x = new BigDecimal( a );
BigDecimal y = new BigDecimal( b );
BigDecimal result = BigDecimal.ZERO;
BigDecimal result = x.add(y);
return String.valueOf(result);
https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html.
Every object has a toString() method in Java.

Prepend zero to byte

I'm reading file and I want to print byte value in 2 digits if it is less than 10 (example if byte=1 it should disply byte=01), I don't want to compare it like this:
if(byte<10){
stringBuffer buf= new stringBuffer();
buf.append("0"+byte);
}
is there any built-in method to do this, just like the format function in vc++?
How about:
String twoDigits = String.format("%02d", myByte);
It's a lot closer to the C way of doing things rather than having to instantiate your own formatter.
You can use DecimalFormat:
NumberFormat nf = new DecimalFormat("00");
buf.append(df.format(byteArray[i]));
Obviously you just instantiate it once outside the loop.
System.out.println(new DecimalFormat("00").format(9));
prints 09 for me.
See java.util.Formatter
java.util.Formatter
The 'a' is 10 in hexadecimal format.
So change your format strings from "%02x" to "%02d"
Take a look at the Formatter class
byte b = ...
System.out.println(String.format("%02x",b));
For "small" values of b this should be fine:
String s = "" + b;
while(s.length() < 2) {
s = "0" + s;
}
I'm not so convenient with java syntax... But here is a way... May be you need to find equalant of right for java
buf.append(right(("00" + byte),2))

Categories