how to cast String with period and comma to int, like
String a "9.000,00"
int b = Integer.parseInt(a);
when I run this code, I get an error message : Exception in thread "main" java.lang.NumberFormatException: For input string: "9.000,00"
If you want to get as result 900000 then simply remove all , and . and parse it with for instance with Integer.parseInt or Long.parseLong or maybe even better use BigInteger if number can be large.
String a = "9.000,00";
BigInteger bn = new BigInteger(a.replaceAll("[.,]", ""));
System.out.println(bn);
Output: 900000
But if you want to parse 9.000,00 into 9000 (where ,00 part is decimal fraction) then you can use NumberFormat with Locale.GERMANY which uses form similar to your input: 123.456,78
String a = "9.000,00";
NumberFormat format = NumberFormat.getInstance(Locale.GERMANY);
Number number = format.parse(a);
double value = number.doubleValue();
//or if you want int
int intValue = number.intValue();
System.out.println(value);
System.out.println(intValue);
Output:
9000.0
9000
final String a = "9.000,00";
final NumberFormat format = NumberFormat.getInstance(Locale.GERMAN); // Use German locale for number formats
final Number number = format.parse(a); // Parse the number
int i = number.intValue(); // Get the integer value
Reference
To do that, you need to use java.text.NumberFormat and NumberFormat.getInstance(Locale.FRANCE) (or another compatible Locale)
import java.text.NumberFormat;
import java.util.Locale;
class Test {
public static void main(String[] args) throws Exception {
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
String a = "9.000,00";
a = a.replaceAll("\\.", "");
Number number = format.parse(a);
double d = number.doubleValue();
int c = (int) Math.floor(d);
System.out.println(c);
}
}
prints 9000 as you want ( and now is an int ) !
If I print every intermediate step :
import java.text.NumberFormat;
import java.util.*;
class test {
public static void main(String[] args) throws Exception {
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
String a = "9.000,00";
a = a.replaceAll("\\.", "");
System.out.println(a); // prints 9000,00
Number number = format.parse(a);
System.out.println(number); // prints 9000
double d = number.doubleValue();
System.out.println(d); // prints 9000.0
int c = (int) Math.floor(d);
System.out.println(c); // prints 9000
}
}
so if Okem you want 9000,00 as you're saying in your comment, you just need
a = a.replaceAll("\\.", "");
System.out.println(a);
which gives you an output of 9000,00
I hope that helps.
Try this -
String a = "9.000,00";
a = a.replace(",","");
a = a.replace(".","");
int b = Integer.parseInt(a);
I think DecimalFormat.parse is the Java 7 API way to go:
String a = "9.000,00";
DecimalFormat foo = new DecimalFormat();
Number bar = foo.parse(a, new ParsePosition(0));
After that, you go and be happy with the Number you just got.
If you want the answer to be 900000 (it doesn't make sense to me, but I'm replying to your question) and put that into an int go with:
int b = Integer.parseInt(a.replaceAll(",","").replaceAll("\\.",""));
as already outlined in the comments.
Related
I am trying to convert float number in Java to integer on the following way:
4.55 = 455
12.45 = 1245
11.1234 = 111234
How can I do it?
One option would be like this:
float number = 4.55f;
int desiredNumber = Integer.parseInt(String.valueOf(number).replaceAll("\\.", ""));
But something like this will only work if the conversion pattern will stay the same. By this I mean the way you want to convert from float to int. Hope this helps.
here is an example
double f1 = 4.5;
String str = new Double(f1).toString();
str = str.replace(".", "");
Integer i = Integer.parseInt(str);
System.out.println(i);
If you want to be able to hanlde arbitrarily large numbers and arbitrarily many decimals, then you can use BigDecimal and BigInteger
BigDecimal number = new BigDecimal(
"5464894984546489498454648949845464894984546489498454648949845464894984546489498454648949845464894984.1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111");
String valueOf = number.toPlainString();
BigInteger desired = new BigInteger((valueOf.replaceAll("\\.", "")));
System.out.println(desired);
Constructor can take double or float if needed
BigDecimal number = new BigDecimal(Double.MAX_VALUE);
BigDecimal number = new BigDecimal(Float.MAX_VALUE);
Something like that :
public int convert( float numbre) {
String nmbre = String.valueOf(numbre).replace(".", "");
return Integer.parseInt(nmbre );
}
You can convert the number to a String, remove the dot, and create a new Long:
private long removeTheDot(Number number) {
return Long.valueOf(number.toString().replace(".", ""));
}
Ka-Bam!
I am using Yahoo's YQL API and fetching the global indices; the issue that I am facing is that for some of the regions I am getting values as:
String change_inpoints = "510.663757";
String change_inpercentage = "+0.095152%";
Could you please tell me how can I round it off after two digits?
Use DECIMALFORMAT.
public static void main(String[] args) {
String s = "2.22234242342342";
double d = Double.parseDouble(s);
DecimalFormat decimal = new DecimalFormat("#.00%");
System.out.println(s);
System.out.println(decimal.format(d));
}
I want to add zero before decimal, if the number starts with decimal itself.
Input: .2345
Output: 0.2345
I'm using DecimalForamtter. I'm avoiding using string appender.
Please suggest.
Thank You
that should give you the expected output:
#Test
public void testFloatLeadingZero(){
float value = .1221313F;
DecimalFormat lFormatter = new DecimalFormat("##0.0000");
String lOutput = lFormatter.format(value);
Assert.assertTrue(lOutput.startsWith("0."));
}
or with String.format:
#Test
public void testFloatLeadingZero(){
float value = .1221313F;
String lOutput = String.format("%.20f", value);
Assert.assertTrue(lOutput.startsWith("0."));
double value2 = .1221313d;
String lOutput2 = String.format("%.20d", value2);
Assert.assertTrue(lOutput2.startsWith("0."));
}
I think you are using Float right? Otherwise you have to replace f with d for Double.
I have used below code and worked in all scenarios. I wanted to get 10 digits including 2 decimal places. It will give me trailing 0s in decimal place also.
DecimalFormat df = new DecimalFormat("00000000.00");
double d1 = 678.90;
System.out.println(df.format(d1));
Output: 00000678.90
Please help me to solve this. I trying to get value from textview and stored as string. Then it converts to double. While converting up to 7 characters functioning normally but if i try to add more than 7 result is 1.23456789E8. Here is my code
String value = tvInput.getText().toString();
\\tvInput is my textView
Double result = 0.0;
Double input1=0.0;
Double input2=0.0;
input=Double.parseDouble(value);
result = input1 + input2;
tvInput.setText(Double.toString(result));
if i give input1 value as 1234567 and input2 as 1234567 i am getting correct result but if give input1 as 12345678 and input2 as 3. the output is 1.2345681E7
The value you get is correct, the issue is with the way you print it.
You're relying on toString for a double output; if you want to guarantee not to have an exponential notation, you should format it using a DecimalFormat, or with String.format;
DecimalFormat myFormatter = new DecimalFormat("############");
tvInput.setText(myFormatter.format(result));
Also see the format documentation
The behavior you describe is consistent with the javadoc. You could use String.format instead.
Either 12345678 and 1.2345678E7 are exactly the same number. No trouble with that
Your trouble is with the representation, if E>6 then toString() use scientific notation. You may want to use NumberFormat for this.
Use String.format: example
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
String i1 = "12345678";
String i2 = "3";
double d1 = Double.parseDouble(i1);
double d2 = Double.parseDouble(i2);
double d = d1 + d2;
System.out.println( String.format("%f", d) );
}
}
Why don't use Integer instead?
String value = tvInput.getText().toString();
\\tvInput is my textView
int result = 0;
int input1 = 0;
int input2 = 0;
input=Integer.parseInt(value);
result = input1 + input2;
tvInput.setText(Integer.toString(result));
I'm doing my first attempts to use BigDecimal. It seems tricky.i am running into an issue and i would like to understand what is causing it.
public static String nominator(String nbrPeople)
{
BigDecimal nom = new BigDecimal("365") ;
BigDecimal days = new BigDecimal("365") ;
int limit = Integer.parseInt(nbrPeople);
for (int i = 0 ; i < limit ; i++ )
{
days = days.substract(i) ;
nom = nom.multiply(days) ;
}
return nbrPeople ;
}
this is part of a larger program. it is a method that should compute something like this:
365 x (365-1) x (365-2) x (365-3) etc depending on the value of nbrPeople passed in.
i would like to understand why i get the following error message:
cannot find symbol
method substract(int)
not looking for a discussion on factorials but rather on the use of BigDecimal (or BigInteger). I'm using BigDecimal because at a later stage i will need to divide, resulting in floating point.
EDIT
EDIT 2
first edit removed (code) to make the post more readable- the correct code has been posted below by a kind programmer
Because the method is named subtract not substract.
And the parameter has to be BigInteger too:
http://download.oracle.com/javase/6/docs/api/java/math/BigInteger.html#subtract(java.math.BigInteger)
You are attempting to subtract an int from a BigDecimal. Since there is no method subtract(int x) on the BigDecimal class, you get the cannot find symbol compiler error.
This should work:
public static String nominator(String nbrPeople)
{
BigDecimal nom = new BigDecimal("365") ;
BigDecimal days = new BigDecimal("365") ;
int limit = Integer.parseInt(nbrPeople);
for (int i = 0 ; i < limit ; i++ )
{
days = days.subtract(new BigDecimal(i)) ;
nom = nom.multiply(days) ;
}
return nbrPeople ;
}
as there is no BigDecimal.subtract(int) method, only a BigDecimal.subtract(BigDecimal) method.
Typo - you misspelled "subtract".
Should be subtract ( with a single s )
Whenever you see cannot find symbol message, you are trying to use a method that doesn't exist or a variable that doesn't exists. Most of the time ( as in this case ) due to a misspelling or because you didn't import the class.
BigDecimal can only subtract another BigDecimal. you are subtracting an int. See
http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#subtract(java.math.BigDecimal)
http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#subtract(java.math.BigDecimal
import java.math.BigDecimal;
import java.util.Scanner;
public class BigDecimal_SumExample {
public static void main(String args[]) {
BigDecimal number1;
BigDecimal number2;
BigDecimal sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of number 1");
number1 = sc.nextBigDecimal();
System.out.println("Enter the value of number 2");
number2 = sc.nextBigDecimal();
BigDecimal a = new BigDecimal(""+number1);
BigDecimal b = new BigDecimal(""+number2);
BigDecimal result = a.add(b);
System.out.println("Sum is Two numbers : -> ");
System.out.println(result);
}
}
**Output is**
Enter the value of number 1
68237161328632187132612387312687321678312612387.31276781237812
Enter the value of number 2
31232178631276123786321712369812369823162319862.32789129819299
Sum is Two Big Decimal numbers : ->
99469339959908310918934099682499691501474932249.64065911057111