Prepend zero to byte - java

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))

Related

Convert string to int with 1st null saving

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));

Converting exponential value in java to a number format

I am trying to read the values from excel sheet using java. When i type more than 10 letters in a cell in excel it is displaying in exponential form like "9.78313E+2". but this is not the real number what i given.
Can any body help me out in this. How can i convert the above exponential form to original number using java language.
Thanks in advance
You can convert as follows,
for example:
new BigDecimal("406770000244E+12").toBigInteger();
Double.parseDouble("9.78313E+2");
gives me
978.313
For more info see the doc.
Following your further queries below, if you've entered 4256411411 and Excel is presenting this as 4.26E+09, putting that value into parseDouble() will only give you 4260000000. If you want the original, perhaps you need to output the Excel file in a fuller format for your Java program, and/or query it using a Java/Excel API (e.g. POI)
Sorry, but none of the answers above Double.parseDouble() and Double.valueOf()... solved my problem, and I continued to get the exponential 'E' value...
This link has a much better approach for the problem, and as I've written there - there is a very good solution:
I needed to convert some double to currency values, and fount that most to the solution are OK but not for me.
The DecimalFormat was eventually the way for me, so here is what I've done:
public String foo(double value) //Got here 6.743240136E7 or something..
{
DecimalFormat formatter;
if(value - (int)value > 0.0)
formatter = new DecimalFormat("0.00"); //Here you can also deal with rounding if you wish..
else
formatter = new DecimalFormat("0");
return formatter.format(value);
}
As you can see, if the number is natural I get - say - 20000000 instead of 2E7 (etc) - without any decimal point.
and if it's decimal, I get only 2 decimal digits.
Hope this will help.
You can use BigDecimal, if you want the exact value that you have in Excel Sheet: -
BigDecimal bd = new BigDecimal("4256411411");
System.out.println(bd.doubleValue());
// If you are sure that's not a floating point number, then use
System.out.println(bd.longValue());
Prints: -
4.256411411E9
4256411411
Try this definitely gona work
double value = 2.06E //real 205809104.13
BigDecimal.valueOf(value)
work for me
Before you read the value from excel sheet format your Column to number.
This may be helps to you
UPDATED
HSSFCell cellE1 = row1.getCell((short) 4);
cellE1.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
Double e1Val = cellE1.getNumericCellValue();
BigDecimal bd = new BigDecimal(e1Val.toString());
long lonVal = bd.longValue();
System.out.println(lonVal);
You can convert easily with the following methods:
Double.valueOf("9.78313E+2").longValue() or
BigDecimal bd = new BigDecimal("9.78313E+2");
long val = bd.longValue();
Assuming that the given number is in a String form.
You can also use wrapper classes :
Double bd=new Double(4445566622);
System.out.println(bd.longValue());
Outputs -4445566622
i had same problem when i only needed String Data that is "1744949451" but it give "1.744949451E9"
so this worked for me
XSSFCell cell = cells.getCell(j);
String value = cell.toString();
if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
//cell.setCellType(XSSFCell.CELL_TYPE_STRING);
value = cell.getRawValue();
}
Log.i("LOG", value + " " + cell.getCellType());
This answer worked for me:
Double bd = new Double(4445566622);
System.out.println(bd.longValue());
// Outputs -4445566622
`Double value = double value ;
Long longValue = value.longValue(); String strCellValue1 = new String(longValue.toString().format("%f",value).replaceAll("\\,?0*$", ""));`
declare a double value and convert to long
convert to string and formated to float the double value finally replace all the value like 123456789,0000 to 123456789
Have to convert the cell into number format before reading the cell value. Below is the code snippet that is used to get the actual value that is in exponential format:
nextCell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
Double doubleValue = nextCell.getNumericCellValue();
BigDecimal bd = new BigDecimal(doubleValue.toString());
long lonVal = bd.longValue();
String phoneNumber = Long.toString(lonVal).trim();
System.out.print("PhoneNumber " + phoneNumber);
Blog has been wirtten to showcase the actual result.
Regards,
Ankur
Try the following pattern:
Double dblValue = Double.parseDouble("1.99E+07");
String str = String.format("%.2f", dblValue);
System.out.println(str);
Output:
run:
19900000,00
BUILD SUCCESSFUL (total time: 0 seconds)

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();
}

in Java, how to delete all 0s in float?

I'd like to change float like this way:
10.5000 -> 10.5
10.0000 -> 10
How can I delete all zeros after the decimal point, and change it either float (if there's non-zeros) or int (if there were only zeros)?
Thanks in advance.
Why not try regexp?
new Float(10.25000f).toString().replaceAll("\\.?0*$", "")
Well the trick is that floats and doubles themselves don't really have trailing zeros per se; it's just the way they are printed (or initialized as literals) that might show them. Consider these examples:
Float.toString(10.5000); // => "10.5"
Float.toString(10.0000); // => "10.0"
You can use a DecimalFormat to fix the example of "10.0":
new java.text.DecimalFormat("#").format(10.0); // => "10"
java.math.BigDecimal has a stripTrailingZeros() method, which will achieve what you're looking for.
BigDecimal myDecimal = new BigDecimal(myValue);
myDecimal.stripTrailingZeros();
myValue = myDecimal.floatValue();
This handles it with two different formatters:
double d = 10.5F;
DecimalFormat formatter = new DecimalFormat("0");
DecimalFormat decimalFormatter = new DecimalFormat("0.0");
String s;
if (d % 1L > 0L) s = decimalFormatter.format(d);
else s = formatter.format(d);
System.out.println("s: " + s);
You just need to use format class like following:
new java.text.DecimalFormat("#.#").format(10.50000);
Format your numbers for your output as required. You cannot delete the internal "0" values.
Try using System.out.format
Heres a link which allows c style formatting
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
I had the same issue and find a workaround in the following link:
StackOverFlow - How to nicely format floating numbers to string without unnecessary decimal 0
The answer from JasonD was the one I followed. It's not locale-dependent which was good for my issue and didn't have any problem with long values.
Hope this help.
ADDING CONTENT FROM LINK ABOVE:
public static String fmt(double d) {
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}
Produces:
232
0.18
1237875192
4.58
0
1.2345

How to format numbers to same number of digits, 0-padded?

I have several strings of different length
"2323"
"245"
"353352"
I need to convert them to string of the same size such as:
"0002323"
"0000245"
"0353352"
How can I automatically add the correct number of 0s in front of each string ?
thanks
Use String.format:
Integer i = Integer.valueOf(src);
String format = "%1$07d";
String result = String.format(format, i);
Using DecimalFormat, String.format, or printf you can format a Number.
Example using DecimalFormat:
NumberFormat formatter = new DecimalFormat("0000000");
String number = formatter.format(2500);
Hope it helps.
Regards!
Or use Apache Commons / Lang:
String s = "245";
String zeroPadded = StringUtils.leftPad(s, 6, '0');
Reference:
StringUtils.leftPad(String, length,
padChar)

Categories