I have a String which contains values like 12:02.Now i splitted this String based on :
and stored into array.Now i have to parse these array values into integer ..
On parsing to Integer from String my 02 becomes 2 only whereas in need 02.
I am not getting how to do it.
Here is my code..
time = request.getParameter("time");
System.out.println(time);
String[] timearr = time.split(":");
hourset=Integer.parseInt(timearr[0]);
minuteset=Integer.parseInt(timearr[1]);
the value of minutset is giving difference..
Please help me.
Thanks in advance..
You can use this one
If you want to see "02" on screen, format it with "%02d" pattern,
System.out.println("%02d", data)
You are confusing the value of a number (2) with its string representation (which can be 2, 02, 002, 000002, 0x02, whatever).
If you're dealing with time, use one of the classes that are more suitable for that, e.g. Date and Calendar.
If you really want to keep the '02', use a String and not an int.
You have to distinguish two things: how number looks like and what number is. For example number 10 may look like "010", "10", "A", "1e1", but it is still the same number.
When you output number on screen with System.out.printf("%d", minuteset), you are asking to format it with simplest format - "2". If you want to see "02" on screen, format it with "%02d" pattern:
System.out.printf("%02d", minuteset)
it's not possible. 02 is becomes 2 only..
02 is not an Integer. 2 is an Integer. and you can not use Integer in this case. but if you want to store it in Integer, you must parse (you must write a custom parser that insert 0 to the first of one digit numbers) it again and show it as String.
That is because an actual number has no leading zeroes as they make no sense at all and are superfluous. In case of integers, if you specify a leading zero yourself, then it'd be treated as an octal value.
In case you want to display the number with a leading zero, then you can use string formatting to achieve this.
int num = 123;
string leadingZeroes = String.format("%05d", num);
Numeric data types are fundamentally incapable of distinguishing between 2 and 02. The underlying bit pattern is identical. If you try System.out.println(02); you'll see 2 as the output, because it just can't tell the difference.
Whether or not to put zeros in front of the number is a formatting issue, and you can only control formatting of a number once you output it as a String again. E.g. try:
String time2 = String.format("%02d:%02d", hourset, minuteset);
And you will get "12:02" again.
Golden rule: If you have numbers and you know that you will not do any math operations or database operations on the numbers, you should keeps those numbers as strings. I don't know if this is a real golden rule, but this is what I follow. lol.
Strings have many power ways to be manipulated, that's why I prefer String if no math/db operations will be done.
Related
I am trying to convert an inputstream to objects and am having trouble with converting the below string to BigDecimal. I get 87.00 as the 0's are ignored. I am experimenting with DecimalFormat. Any help is appreciated. Thanks!
E.g. 0087 has to be converted to 00.87
You seem to indicate in comments that the initial string, "0087", is a fixed-point representation with two decimal places, there therefore being an implicit decimal point before the last two digits. There are several ways that you could convert that to a corresponding BigDecimal, but myself, I would go with this:
BigDecimal result = BigDecimal.valueOf(Long.parseLong("0087"), 2);
The key here is to understand that BigDecimals have two characteristic properties: an arbitrary-length sequence of decimal digits, and a scale conveying the place value of the least-significant digit, in the form of the number of digits to the right of the decimal point. The particular factory method demonstrated above accepts those as separate arguments, though it only works if the digit string is short enough to be represented as a long. The 2 corresponds directly to the number of (implicitly) fractional digits in your input.
Outputting the resulting BigDecimal as "00.87" instead of "0.87" is a separate issue, but doable, if it's really something you want.
Try this code
String str="0087";
int pos=str.lastIndexOf("0");
String resultat=str.substring(0,pos+1);
resultat+=".";
resultat+=str.substring(pos+1);
System.out.println(resultat);
new BigDecimal(resultat);
How to declare a numerical variable in Java that is to hold a digit value with a fixed length of 3 digits always. That is if i input 0, it should be formated to 000, if i input 31 then it should be formated to 032 and if i input 100 then it should remain 100. I need this for receiving and storing three digit integer value that is sent via rest response as error codes. I tried the normal int and Integer but the preceeding zeros are always removed. Thanks for the help.
It's not a property of a numerical variable, but a way of formatting it (of converting it to a string).
It can be done with: String.format("%03d", x) (x being a numerical variable).
I tried the normal int and Integer but the preceeding zeros are always
removed.
This behavior is expected. The int type cannot represent numbers with preceeding zeroes; just as you want. To achieve the 3-digit effect, you have to format to a String everytime you want to display the integer.. You can do it this way:
String.format("%03d", number); //number is the int.
If number is 4, using the code snippet above will output: 004.
I hope this helps.. Merry coding!
This is a formatting problem rather than a type problem
you should look at the String.format method or the DecimalFormat class
I was trying to convert the String to int. However, its encounter error throw a NumberFormatException.
java.lang.NumberFormatException: For input string: "07221255201"
Code :
int value = Integer.valueOf(itemData.get(row).ERP_Customer_Item.trim());
Kindly advise.
7221255201 is out of primitive int range. You should use long type.
This should work fine:
long value = Long.parseLong(itemData.get(row).ERP_Customer_Item.trim());
And for other contexts, try to have a practice of keeping primitive type ranges in mind when you write code. It is like having a hammer set consisting of hammers of different size and using the appropriate one in the context. For example, if you know that a particular variable will always be in the range of [-128,127] you should use short instead of int since you will waste a lot of bits in the latter case.
Your number is larger than Integer.MAX_VALUE (2^31 - 1, or 2147483647), so it can't be parsed into an int.
Be careful converting from strings to numbers. Whatever created that number wasn't using java ints.
You can use a Long.parseLong to convert to a long, or Long.valueOf to get a Long (object instead of primative) in this case, but why are you converting from string in the first place? You're losing information (in this case the leading zeros which may or may not be important depending on what you do with the data). Conversion has a way of biting back somewhere down the line.
I have an ArrayList that i am inputting numbers into like
23466012.83
23466413.39
23466411.94
etc.
but when i reprint them from the array after i sort them they are reprinted like this
2.346601283E7
2.346641339E7
2.346641194E7
Why does java do this and how can this be fixed? (I want the format to be the same as when it was input)
Thanks!
Please review how Java handles primitive types and their related objects. By adding a "double" (lowercase) primitive type into a List, they are converted into "Double" objects, because List in Java can only hold objects, not primitives.
Therefore when you later output the Double object, it actually uses the simple toString() method of class Double to format the line. And this is implemented in a way to print the full range of Double in a readable format, this is why it chooses the so-called Scientific Notation with exponents display.
By using a more useful formatter, e.g. the Formatter class as mentioned in the comment or the MessageFormat class, you can better control how the output looks like.
Why does java do this
Java merely prints out your Double values using the default number format.
and how can this be fixed?
By explicitly specifying the desired number format.
I want the format to be the same as when it was input
First of all, you'll need to understand that you can't get "the same format as when it was input" because that information is irretrievably lost. It cannot be determined by inspecting a Double value how many significant digits were used to parse it.
If all you need is printing with two decimal places, one way to achieve it is with this statement:
System.out.format("%.2f%n", 23466012.83);
If, by any chance, you are not bound to using Double as the container of your numeric values, you may also consider BigDecimal, which can exactly represent an arbitrary value in decimal notation. It takes a lot more memory and is a lot slower in computation, but for many use cases neither of those may matter much. A larger issue is that the division of BigDecimal is an involved process because, by default, the API will insist on producing an exact result, which will fail for things as simple as 1/3.
System.out.format("%f%n", value);
Where value is the double primitive variable you want to print to sysout the screen.
Remove the %n if you want to continue printing on the same line.
There are existing answers that indicate how to format the output if you want the numbers output with two decimal places, regardless of how they were input.
If you really mean "I want the format to be the same as when it was input" there is only one practical option - store the input string. You can parse it as a double or BigDecimal for validation and when you need it as input to arithmetic, but always output it using the original.
how can i get for example the integer codeInt=082 from String code='A082'
i have tried this:
int codeInt = Integer.parseInt(code.substring(1,4));
and i get codeInt=82 ,it leaves the first 0 but i want the full code '082'.
i thought of parseInt(String s, int radix) but i don't know how .
any help will be appreciated .
thanks.
An integer just stores a number. The numbers 82 and 082 (and 0082 and 000000082 for that matter) are exactly the same (unless you put them into source code in some languages in that manner, then you'll get a compiler error)1.
If you desperately need the leading zero, then you should either leave it as a string, or format the number appropriately for output later.
1 Due to the C designers having the ingenious idea that writing octal constants with a preceding zero would be cool. As if something like 0o123 would have been that hard to implement once you already got 0xf00 ...
The number 82 and 082 and 0082 is mathematically the same number, and is represented by the same sequence of bits. You can't encode the number of leading zeroes in an int (although you can certainly print it with whatever format you choose).
Note also that the number 082 is different from the Java literal 082, which is an (invalid) octal literal.
int i = 010;
System.out.println(i); // this prints 8
082 is not an integer. It's a string representing the integer 82. If you require leading zeros to be left untouched, you will need to work with strings. If you only need it to print 082, you can use java.text.MessageFormat or System.out.format() or other, similar solutions to print it that way.
If you want 0000123 then you need to threat a variable as a String instead of Integer. Simply: 123 is equal to 000123 and 0123 and 0000...1 billion zeros here...000123.
But if you just want to display a number with fixed length then use System.out.format().