I have some issue like this
in my textview Rs. 99.99
String val = textview.getText().toString();
Result :: val :: Rs.99.99
i am converting that into float using this way
float value = Float.parseFloat(val);
i am getting NumberFormatException: Rs.99.99 cannot convert
any one guide me
You can do the following before converting it to float
String substring = str.length() > 2 ? str.substring(str.length() - 3) : str;
You can try this way.
System.out.println(Float.parseFloat("Rs.99.99".substring(3)));
Note: You need to make sure the string always contain "Rs." in the beginning.
i am getting numberFormat Exception Rs.99.99 cannot convert
Yes, because in method
Float.parseFloat(String s);
You get
NumberFormatException -- if the string does not contain a parsable float.
And In your case it isn't,
So best option is to apply Validation to enter only floating point numbers inside text View.
It's not entirely clear what the problem is (do all the strings that cause problems begin with Rs., or are users putting other kinds of garbage at the beginning of the input)? Here's a way to remove all characters from the string, up to (but not including) the first digit:
val = val.replaceFirst("^[^0-9]*", "");
This finds the first occurrence of a pattern that starts at the beginning of the string (the first ^) and consists of 0 or more occurrences of nondigits ([^0-9]).
Related
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.
String classs = "java1110======$500.50";
and I want to extract 500.50 from the String value. What should I do?
I tried replace() but it gives me 111050050.
try this :
class.substring(class.lastIndexOf("$") + 1);
Use the ASCII range of numbers to set up the condition that whenever the ASCII value of a particular character comes up in between you put it in a character array,or any string variable,it's all on your discretion.
Hope this helps
I'm trying to ensure that a given string is a valid double. Most answers to this sort of question suggest using Double.parseDouble(inputString). However this isn't as robust as I'd hope. For instance if I enter a String such as "1one" Double.parseDouble("1one") will output "1" as opposed to returning an exception for an invalid double.
I've tried to get around this by iterating over the string and ensuring that every number is a digit:
for (int i = 0; i < number.length(); i++) {
previousChar = number.charAt(i);
if (!Character.isDigit(number.charAt(i))
&& number.charAt(i) != '.'
&& number.charAt(i) != ',') {
return null;
}
}
But for cases such as "20..02" or "20,,02" this will simply return 20. I was wondering what the best way to account for cases such as these would be.
Good question. Depending on the users, you may need to be careful of differences between locales. Some places use , as a thousand separator others as a decimal point. You can find the locale-specific value using:
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance();
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
char decimalSeparator = symbols.getDecimalSeparator();
I would suggest writing a regular expression for your exact requirement rather than doing the matching manually. Remember to escape . if you want it to match . and not "any character".
Alternatively, you may be able to use parseDouble which does seem to throw an exception for "1one" after all:
System.out.println(Double.parseDouble("1one"));
For me, it produces:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1one"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Double.parseDouble(Double.java:540)
You could use the Validator framework and use the DoubleValidator from commons-validator.
DoubleValidator validator = DoubleValidator.getInstance();
validator.validate("1one");
Parsing strings to doubles is fraught with danger. For example, in France, 1,234 is a number just a little greater than 1. They use . to separate round thousands and , to denote the start of the decimal portion.
The best way to check if a string is a valid number is to use NumberFormat to attempt to parse it and treat any exceptions thrown as an indication that the string is not a valid number. NumberFormat allows you to associate a locale:
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH/*for example*/);
double myNumber = nf.parse(myString); /*will throw an exception if not valid*/
I would use Double.parseDouble, because, contrary to what you believe, it does throw a NumberFormatException for 1one.
public class k {
public static void main(String argv[]) {
double d = Double.parseDouble("1one");
}
}
Output:
Exception in thread "Main Thread" java.lang.NumberFormatException: For input string: "1one"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Double.parseDouble(Double.java:510)
at k.main(k.java:3)
If I wanted to allow both , and . and not just the decimal point specified by the locale, I would replace any , and . with the locale specified decmial point.
Using a simple regex, you can check if it contains any non numerical characters like so:
String input = "1one2";
String numerical = input.replaceAll("[^0-9.]", "");
if (input.equals(numerical)) // If you remove all non numbers, still the same string
After which you can parse it for a double.
Hello Im new to programming
and as title I was wonder how you can find last digit of any given number?
for example when entering in 5.51123123 it will display 3
All I know is I should use charAt
Should I use while loop?
thanks in advance
You would want to do something like this:
double number = 5.51123123;
String numString = number + "";
System.out.println(numString.charAt(numString.length()-1));
When you do the number + "", Java "coerces" the type of number from a double to a string and allows you to perform string functions on it.
The numString.length()-1 is because numString.length() returns the count of all the characters in the string BUT charAt() indexes into the string and its indexing begins at 0, so you need to do the -1 or you'll get a StringIndexOutOfBoundsException.
You can use below function simply and you can customize data types accordingly,
private int getLastDigit(double val){
String tmp = String.valueOf(val);
return Integer.parseInt(tmp.substring(tmp.length()-1));
}
You can't use charAt on a floating point variable (or any other data type other than Strings). (Unless you define a charAt method for your own classes...)
You can, however, convert that floating point number to a string and check the charAt(str.length()-1).
Convert your float variable to string and use charAt(strVar.length - 1).
double a=5.51123123;
String strVar=String.valueOf(a);
System.out.print(strVar.charAt(strVar.length -1);
Double doubleNo = 5.51123123;
String stringNo = doubleNo.toString();
System.out.println(stringNo.charAt(stringNo.length()-1));
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;
}