I want to print digit value but its not working [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to print 157.30 but print 15730
The code is
String Printprice="$157.30";
double value = Integer.parseInt(Printprice.replaceAll("[^0-9]",""));
Output:
15730

First problem
Printprice.replaceAll("[^0-9]","") removes everything that is not a digit, also the decimal point.
If you want to keep the decimal point, you need to change the regex to [^0-9.] (note the . after the 0-9):
Second problem
Furthermore, Integer.parseInt parses an int, not a double. If you want a double, you should use Double.parseDouble instead:
double value = Double.parseDouble(Printprice.replaceAll("[^0-9.]",""));
Other approach
If you just want everything after the first character, you can use String#substring in order to remove the first character:
double value = Double.parseDouble(Printprice.substring(1));
Things woth noting
It shoud also be noted that variables should be camelCase by convention. Instead of Printprice, you should use printPrice:
String printPrice="$157.30";
double value = Double.parseDouble(printPrice.substring(1));
Yet another thing worth noting is that you shouldn't use IEEE floating point numbers for currency calculations as those are a bit weird. Instead, you may want to save the price in cents (as a long value) or use NumberFormat/Currency as suggested by Achintya Jha.

Try using NumberFormat class
https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html
NumberFormat numberformat = NumberFormat.getCurrencyInstance();
Number number = null;
try {
number = numberformat.parse("$157.30");
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(number.toString());

String price ="$157.30";
float value = Float.parseFloat(price.replace("$",""));
System.out.println(value);

Related

Issue creating a calculator [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm a beginner at java and I've been trying to make a calculator using Swing. So far everything is good, but I'm having trouble with how the number pad will work. I want the calculator's output to be a float value, but I want it to be so that if you click "1", the output will display "1", not "1.00". How could I go about this?
Also, I cannot think of a way to append a number to another number. For example, if I input 1 then input 2, the output would be 1.02, not 12. How do I get the program to make the output be a whole number when possible?
For the first question: You first want to check that there are no digits after the decimal point when just displaying 1 instead of 1.00. To do so you can check that this actually is the case with this if statement:
if(number % 1.0f == 0)
next, you want to convert this number into a string that just displays the number without the decimal points, to do so you can cast number to an int and then convert it into a string with:
String.valueOf((int) number)
For the second question: To append a new digit to the number I would suggest generating a string with the number the user enters using StringBuilder. In practice it would look something like:
StringBuilder sb = new StringBuilder();
// when user presses "2" button for example:
sb.append("2");
In the end you want to convert this generated String into a float in order to perform calculations on it, which you can do with:
float value = Float.valueOf(sb.toString());

How to take only numbers in a string? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
If you prompt the user for a price and they input $25.50, how would I take out the numbers and store them as a Double so that I can use them in equations.
I have tried,
System.out.println("What is the price of the product(e.g. 35.21)?");
price = scanner.nextLine();
price_2 = price.replaceAll("[^0-9]", "");
price_3 = Double.parseDouble(price_2);
System.out.println(price_3);
But it does not maintain the decimal.
You can use a regex to strip out all non-numeric characters from the String, while leaving the decimal point.
Then, just parse the string to a double:
String str = "$25.50";
double dbl = Double.parseDouble(str.replaceAll("[^0-9,.]",""));
System.out.println(dbl);
In your code, you were removing the decimal point as well. Simply add the ,. to your regex.

I'm a Java beginner- Convert String value to Integer using JTextField [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have created a simple java program that takes a string input from user through 2 boxes of Jtextfields and then convert it to integer.
These 2 integer values are then converted to decimal values by dividing them.
The decimal values are then seen by the user with a dialog box (basically a fraction to decimal converter)
When I run the program I get errors that I do not understand.
my code
code error
It must throw NumberFormatException if you try to parse it to integer.
Check before parsing. or handle Exception properly.
Exception Handling*
try{
int i = Integer.parseInt(input);
}catch(NumberFormatException ex){ // handle your exception
...
}
or
- Integer pattern matching -
String input=...;
String pattern ="-?\\d+";
if(input.matches("-?\\d+")){ // any positive or negetive integer or not!
...
}

How can I get the results of multiplying 2 doubles, and allow up to 1% error? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Lets say I have program that will generate 2 random doubles, and then asks the user what is the answer.
An example would be the code below, given that num1 and num2 is randomly generated, and userAnswer is the answer that the user has keyed in.
if(num1 * num2 == userAnswer)
{
System.out.Println("You are right!");
}
I understand that multiplying doubles would never be accurate, but how can I change this code to allow errors up to 3 decimal points? I want the console to still display "You are right", even though the answer is 2.1453000001 and the user answers 2.145.
If you're trying to check for up to one percent error you could use
quotient = userAnswer / (num1 * num2);
if (quotient > 0.99 && quotient < 1.01) {
This of course assumes that the correct answer is not 0.0.
You can try with DecimalFormat.
Eg:
double d=2.1453000001;
double formatted= Double.parseDouble(new DecimalFormat("#.###").format(d));
System.out.println(formatted);
Output:
2.145
You can try
public static String format(String format,Object... args)
if you don’t want to print out the String and just want to format it for later use, you can use the static format method of the String
class (sort of like sprintf in C). It works in exactly the same way as
printf as far as formatting is concerned, but it doesn’t print the
String, it returns a new formatted String.
Floating point formatting
%f : will print the number as it is.
%15f : will pint the number as it is. If the number has less than 15 digits, the output will be padded on the left.
%.8f : will print maximum 8 decimal digits of the number.
%9.4f : will print maximum 4 decimal digits of the number. The output will occupy 9 characters at least. If the number of digits is not enough, it will be padded
For Example:
double d=12.23429837482;
String s = String.format("%.3f", d);
System.out.println(s);
Output:
12.234

Put only numeric strings into hashmap [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to build a hashMap from an ArrayList which contains all the variables I need plus their respective values.
The problem is, my arrayList contains variables with non numeric values (eg: var1 = "*$&/#"). How could I filter the data contained in the arrayList to get only the numeric strings.
I tried using regular expressions but the data get filtered too much and some of the variables I need get lost. I guess i'm not using the legit regex. So I tried matching the following regex and if not, assign "0" to my variable. Here's roughly what I've tried thus far:
private static final String REGEX = "-?\\d+(\\.\\d+)?";
//...
if (val_ens1_sol.matches(REGEX) && val_ens1_bord.matches(REGEX)) {
reslutatsMap.put(key_ens1_sol, val_ens1_sol);
reslutatsMap.put(key_ens1_bord, val_ens1_bord);
} else {
val_ens1_sol = "0";
val_ens1_sol = "0";
}
This was already answered somewhere else (How to check if a String is numeric in Java) but to discuss the possibilities: Either you assume that you have numeric strings, parse the string is integer or double and catch the number format exception, or you use a regex.
You can do this using BigDecimal, which will parse all integers/decimal point floats/scientific floats:
try {
new BigDecimal(val_ens1_sol);
new BigDecimal(val_ens1_bord);
} catch (NumberFormatException ignored) {
// deal with at least one value not being a number
}

Categories

Resources