java left integer pad with zero - java

How can I get an Integer to be two digits. If it's under 10 it would show 01,02, etc. I want to keep the Integer as an Integer. String.format gives a string. How can I do this with Decimalformat for ex
Decimalformat df = new Decimalformat(???);

If you want to keep the value as an int or Integer, there's nothing to be done here. A number doesn't have a format - it just has a value. For example, an int isn't "in decimal" or "in hex" or "in binary" - if you write
int x = 16;
int y = 0x10;
those are the exact same values.
The idea of "padding" only makes any sense when it comes to a textual representation of the number - which is when you end up with a string.

you do something likewise, but directly you can't get into int or Integer
NumberFormat formatter = new DecimalFormat("00");
String s = formatter.format(1); // ----> 01

Related

Finding number of digits before a decimal point in java

I have declared the variable for the double I'm using:
z= 345.876;
Now I want to display the number of digits that come before the decimal point. I tried to do the following:
String string_form = new Double(z).toString().subString(0,string_form.indexOf('.'));
double t = Double.valueOf(string_form);
I get an error saying: 'The method subString(int, int) is undefined for the type String'
Then a quick fix shows to change it small case s as: substring. However the error then changes to the string, 'string_form' which says it's not initialized. Any ideas on what to do?
And also how would I modify that to find the number of digits that come after a number? I know in the part
.indexOf('.')
I'd replace the decimal point with a number but how would i change it so that it displays how many digits come AFTER the number, not before? thanks. and yes I have imported the decimalformat text lang.
You're trying to use string_form before you have actually created it.
If you break
String string_form = new Double(z).toString().substring(0,string_form.indexOf('.'));
double t = Double.valueOf(string_form);
into
String string_temp = new Double(z).toString();
String string_form = string_temp.substring(0,string_temp.indexOf('.'));
double t = Double.valueOf(string_form);
Then it should work.
To get the numbers after the decimal point just take the digits from period until the end of the number.
String string_temp = new Double(z).toString();
String string_form = string_temp.substring(string_temp.indexOf('.'), string_temp.length());
double t = Double.valueOf(string_form);
As others have pointed out though, there are many better ways than converting to string and checking for period and reconverting.
The number of decimal digits before the decimal point is given by
(int)Math.log10(z)+1
The number of decimal digits after it is imprecise and depends on how much precision you use when converting to decimal. Floating-point values don't have decimal places, they have binary places, and the two are incommensurable.
just convert the double to a string. find the index of . with indexOf. get the length of the string. subtract the index of . from the length and you should have the count.
String string_form = Double(z).toString();
int index = string_form.indexOf('.');
double d = Double.parse(string_form.substring(0, index+1));
If the numbers are small, you could try
int i = (int) z;
or
long l = Math.round(z);
You're using string_form in the expression string_form.indexOf('.'), but it's not initialized yet, because it's only set after the call to substring(). You need to store the value of toString() in a temporary variable so you can access it in the call to substring(). Something like this
String stringForm = new Double(z).toString();
stringForm = stringForm.substring(stringForm.indexOf('.'));
There are other and better ways to do this, however. Math.floor(z) or even just a cast (long)z will work.
Could do this, for examble:
Integer.parseInt(String.valueOf(possibleBirths).split(".")[0]);
You can do the next thing:
Double z = 345.876;
int a = t.intValue();
int counter = 0;
while(a != 0) {
counter++;
a = a / 10; }
System.out.println(counter);

Removing a decimal point in java

I am wanting to store an integer named Amount, I want it to be stored in pence so if the user entered 11.45 it would be stored as 1145. What is the best way to remove the decimal point? Should I be using decimalFormatting in Java?
Edit:
It is entered in string format, was going to covert it to an int. I will give one of your solutions ago and let you know if it works but not sure which one would be the best.. Thanks everyone.
times it by 100 and cast as int. Use decimal formatting is double / float are too inaccurate which they may be for money
If the user input is in the form of a string (and the format has been verified), then you can strip out the decimal point and interpret the result as an integer (or leave it as a string without the decimal point).
String input = "11.45";
String stripped = input.replace(".", ""); // becomes "1145"
int value = Integer.parseInt(stripped);
If it's a float already, then just multiply by 100 and cast, as #user1281385 suggests.
What about convert to float, multiply by 100 and then convert to int?
String pound = "10.45"; // user-entered string
int pence = (int)Math.round(Float.parseFloat(pound) * 100);
This might be also useful: Best way to parseDouble with comma as decimal separator?
Tested and works. Even if the user enters a number without a decimal, it will keep it as such.
double x = 11.45; // number inputted
String s = String.valueOf(x); // String value of the number inputted
int index = s.indexOf("."); // find where the decimal is located
int amount = (int)x; // intialize it to be the number inputted, in case its an int
if (amount != x) // if the number inputted isn't an int (contains decimal)
// multiply it by 10 ^ (the number of digits after the decimal place)
amount = (int)(x * Math.pow(10,(s.length() - 1 - index)));
System.out.print(amount); // output is 1145
// if x was 11.4500, the output is 1145 as well
// if x was 114500, the output is 114500

Convert cents to euro with NumberFormat

I have a long type value which represents cents in currency. I try to convert it to euros. So, I did the following:
long val = 348;
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.FRANCE);
System.out.println(nf.format(val/100));
I thought the above code will print out 3,48 € but I got 3,00 €. Why?
because val/100 is an Integer operation, so the deciaml part is stripped away. For instane
int i = 1; int result = i / 2; will give you 0
Change to System.out.println(nf.format(((float)val/100)));
To force floating point arithmetic , you can use a double literal 100.0 or float literal 100.0f :
System.out.println(nf.format(val/100.0));

Converting a String that contains decimal to Long

I have following sample (link to ideone).
long lDurationMillis = 0;
lDurationMillis = Long.parseLong("30000.1");
System.out.print("Play Duration:" + lDurationMillis);
It throws an exception:
Exception in thread "main" java.lang.NumberFormatException: For input string: "30000.1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Long.parseLong(Long.java:419)
at java.lang.Long.parseLong(Long.java:468)
at Main.main(Main.java:9)
But why it wont let me convert that number to a string directly ?I can convert number to integer and than convert to double . But is there any other way ?
The value 30000.1 is an invalid long value. You could parse the double value first:
lDurationMillis = (long)Double.parseDouble("30000.1");
You could use BigDecimal in this case:
BigDecimal bd = new BigDecimal("30000.1");
long l = bd.setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
System.out.println(l);
The title says converting string to long, first question is about coverting number to string, next statement about converting number to integer to string. I am confuse.
But for anything to do with floating points, I have to point you at obligatory reference What Every Computer Scientist Should Know About Floating-Point Arithmetic .
In java, int and long do not have fractional parts, so a string like 3000.1 cannot be covnerted to one of these. It can be converted to float or double but if you read the above article you will realize that the coversion can be lossy, i.e. if you canvert that double back to a String you may not get the original 3000.1 back. It will be something close, for appropriate defintion of close, but may not be same.
If you want to use exact precision then BigDecimal is your friend. It will be much slower then the number types, but it will be precise.
Because long can't have fractional part, you could convert it to double and then cast it to long ignoring fractional part
You can do NumberFormat handling as below :
long lDurationMillis = 0;
try{
NumberFormat nf = NumberFormat.getInstance();
lDurationMillis = nf.parse("30000.1").longValue();
System.out.print("Play Duration:" + lDurationMillis);
}catch(ParseException e)
{
e.printStackTrace();
}
Output:
Play Duration:30000

Detect Java NumberFormat inaccuracy

I want to parse an integer accurately, one that has been potentially formatted according to the current locale. If I didn't parse the integer accurately, I want to know it. So I use:
String string = "1111122222333334444455555";
Locale locale = Locale.getDefault();
NumberFormat numberFormat = NumberFormat.getIntegerInstance(locale);
numberFormat.setParseIntegerOnly();
Number number = numberFormat.parse(string);
Obviously "1111122222333334444455555" represents a big number, bigger than a Long can handle. So NumberFormat gives me... a Double??
I guess I would have expected to receive a BigInteger rather than a Double, especially since I asked for an integer-specific number formatter. But never mind that; the bigger problem is that the double value I get back is 1.1111222223333344E24! This is not equal to 1111122222333334444455555!!
If NumberFormat gives me a parsed value that does not equal that stored in the input string, how do I detect that?
Put another way: "How can I know if the Double value I get back from NumberFormat is exactly equivalent to the integral value represented in the original string?"
The javadocs for parse() state that it will return a Long if possible, otherwise it will return a Double. So just check that the return value is a Long.
"Returns a Long if possible (e.g., within the range [Long.MIN_VALUE, Long.MAX_VALUE] and with no decimals), otherwise a Double."
"How can I know if the Double value I get back from NumberFormat is exactly equivalent to the integral value represented in the original string?"
If it returns a Double, then it is not exactly equivalent to your integral value because a Double cannot accurately represent values at that magnitude. Concrete example:
Number a = numberFormat.parse("-9223372036854775809"); // Integer.MIN_VALUE - 1
Number b = numberFormat.parse("-9223372036854775810"); // Integer.MIN_VALUE - 2
System.out.println((a.equals(b))); // prints "true"
Number c = numberFormat.parse("-9223372036854776800");
System.out.println((a.equals(c))); // prints "true"
For you question -
If NumberFormat gives me a parsed value that does not equal that stored in the input string, how do I detect that?
You can use
if(number.toString().equals(string))
//Parsed correctly
else
//Invalid parse
This might not be the solution but worth notice.
public static void main(String[] args) {
String string = "1111122222333334444455555";
Locale locale = Locale.getDefault();
NumberFormat numberFormat = NumberFormat.getIntegerInstance(locale);
numberFormat.setParseIntegerOnly(true);
Number number = numberFormat.parse(string);
BigDecimal b = new BigDecimal(number.toString());
System.out.println(b.toBigInteger());
}
Output of this code is : 1111122222333334400000000
As you can see this is not equal to the number in the actual string , so their might be an overflow occoured.

Categories

Resources