Convert to int from String of numbers having comma - java

I have value like this:
String x = "10,000";
I want to convert this to int.
I can convert it by removing comma like below:
String y = x.replace(",", "");
int value1 = Integer.parseInt(y);
But I don't want to do it like above.
Any other suggestions like inbuilt function? Or any other recommended ways for this?

You can simply:
NumberFormat.getNumberInstance(Locale.UK).parse(x);
Read about:
NumberFormat
Locale.UK and others.

Try this:
NumberFormat format = NumberFormat.getInstance(Locale.US);
Number number = format.parse("10,000");
// Now you can get number values from the object (like int, long, double)
System.out.println(number.intValue());
Output:
10000
Note: If you string contains values after decimal point, you need to use number.doubleValue to retain the precision because number.intValue() will simply ignore values after decimal points.

Use any one of these:
NumberFormat.getNumberInstance(Locale.ENGLISH).parse("10,000").intValue();
NumberFormat.getNumberInstance(Locale.US).parse("10,000").intValue();
NumberFormat.getNumberInstance(Locale.UK).parse("10,000").intValue();

Related

How to print entire number even after removing decimal point?

I have a number as
Double d = 100.000000;
I want to remove the decimal point and print the values as 100000000
(Note I am using java)
It is impossible. double doesn't store zeroes after decimal point so 1.0000 is equal to 1.0.
Hint: you can use BigDecimal for this. It have scale.
I'm afraid 100.000000 does not equal 100000000 and as mentioned by #talex, double doesn't store the zeros after the decimal point.
Your best bet is to use a String and remove the . manually:
String s = "100.000000";
System.out.println(s.replaceAll("\\.", "")); //note '.' needs to be escaped
Output:
100000000
You could parse it as a Double then if necessary.
Format the value using String.format and the remove the separator.
double d = 100.000;
String formatted = String.format(
Locale.US, //Using a Locale US to be sure the decimal separator is a "."
"%5f", //A decimal value with 5decimal
d) //The value to format
.replace(".", ""); //remove the separator
System.out.println(formatted);
100000000
Other examples :
100.000123456 > 100000123
You can see that the value is truncated, it is important to understand that.
Note that I have set the String to have 5 decimal number, but this up to you.
the double does not store the number as 100.0000 it just stored as 100.0 that means any unnecessary zeros on the right will be deleted but if the number was like this 100.01234 u can use this trick
Double d = 100.01245;
String text = Double.toString(d);
text.replace(".","");
d = Double.parseDouble(text);
or u can store the number as sting from the beginning
String text = "100.000000";
d.replace(".","");
double d = Double.parseDouble(text);

Trimming text in java

is java have method to trimming text/string? like this one :
int comaNumber = input.nextInt();
string number = "234,56789";
int coma = number.indexOf(",");
string number = number.substring(0,coma(comaNumber+1));
note : it will search coma character and then it will trim the number based on amount of coma in comaNumber, the result is 234,56 (works)
is any method in java to trimming decimal number to simplify my works? (not trim() function)
Edit: the number of decimal place is specified by user input.
The easiest way is to use DecimalFormat. Although, to get that working with a comma you will need to modify the FormatSymbols.
It would be something like this:
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');//this tels DecimalFormat to use ',' as the decimal separator
String pattern = "#.00";//this means that you want only 2 decimals
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
System.out.println(decimalFormat.parse("221012,28").doubleValue());
System.out.println(decimalFormat.format(1234.123121));
That prints
221012.28
1234,12
You could try using String.format. First switch the comma with a period. For example,
number = number.replace(",",".");
double y = Double.parseDouble(number);
String x = String.format("%.2d",number);
x = x.replace(".",",");
First, you replace the comma with a period. Then you use the parseDouble method(documentation https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)). Then you use String.format to save it with only two places after the decimal point. Then change decimal back to comma.
Hope this helps!
As far as I know, there is no such method. My advice is to create your own method, and then reference it whenever you need it.

Convert String to Number with Format

I was wondering if there is an existing method to convert a formatted number String to number, such as "123,456.78" to 123456.78
Basically, unlike DecimalFormat function, which turns a double variable to a String following that a given format such as "###,###.##" pattern. I want to implement a reverse of this functionality, which turns a String with "###,###.##" format to a double. Is there APIs to do this?
Thank you.
You should have looked through the documentation for DecimalFormat and its superclass. You would have discovered that it has not only format methods, but also parse methods like this one.
The easiest way to do what you want is:
NumberFormat format = NumberFormat.getInstance();
Number value = format.parse(string);
// If you specifically want a double...
double d = value.doubleValue();
You will have to catch ParseException and deal with it. How you do that depends on what you want to do when your string does not represent a valid numeric value. If it's user input, you may want to ask the user to enter the text again.
Here is a simple way to do this
String number = "20,000,000";
int x = Integer.parseInt(number.replace(",", ""));
System.out.println(x);
You just replace the char's that not belong to a number with "" and then parse it into a primitive.
String number = "20,000,000.56";
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(5);
double x = Double.parseDouble(number.replace(",", ""));
System.out.println(df.format(x));
It is a bit different for a Double cause it will display the exponential output and you'll have to prevent that. The code above does that.
df.format(x)
Returns a String but you can cast it with the Double.parseDouble method
Here's a method using a Regex and the replace method if you have more than one delimiter and you know them all :
Let's say the delimiters here are "-" and ","
double x = Double.parseDouble(number.replace("[-,]", "");

Parsing a String with an Exponent (Java)

I have a string similar to: 7.6E+7.
My question is simple: How do I turn this into its corresponding number: 76000000?
I have tried using substring to isolate the E+7 part, then parse the 7 part, then move the decimal places over 7. Is there an easier way to do this?
Thank you!
long n = Double.valueOf("7.6E+7").longValue();
System.out.println(d);
// prints 76000000 to the output.
I suggest using Double.parseDouble():
double val = Double.parseDouble(str);
where str is the input string.
You can use Double.parseDouble() to get it as a number.
String e = "7.6E+7";
System.out.println(Double.parseDouble(e));
Giving the output 7.6E7. If you do not want the E in the output you can use
NumberFormat f = NumberFormat.getInstance();
f.setGroupingUsed(false);
System.out.println(f.format(Double.parseDouble(e)));
Which will give you the output 76000000 without casting to a whole number. Eg adding 0.1 to the number will give the output 76000000.1
If you are sure the number can ultimately be cast into an integer without losing precision than alternatively you could do:
int d = (int) Double.parseDouble("7.6E+7");
System.out.println(d);
Which prints 76000000 to the output.

Java: string tokenizer and assign to 2 variables?

Let's say I have a time hh:mm (eg. 11:22) and I want to use a string tokenizer to split. However, after it's split I am able to get for example: 11 and next line 22. But how do I assign 11 to a variable name "hour" and another variable name "min"?
Also another question. How do I round up a number? Even if it's 2.1 I want it to round up to 3?
Have a look at Split a string using String.split()
Spmething like
String s[] = "11:22".split(":");;
String s1 = s[0];
String s2 = s[1];
And ceil for rounding up
Find ceiling value of a number using Math.ceil
Rounding a number up isn't too hard. First you need to determine whether it's a whole number or not, by comparing it cast as both an int and a double. If they don't match, the number is not whole, so you can add 1 to the int value to round it up.
// num is type double, but will work with floats too
if ((int)num != (double)num) {
int roundedNum = (int)num + 1;
}

Categories

Resources