Multiplying with a string in java - java

I have a string and want to multiply that string by .174.
I have String strNumber = numberText.getText();. How to I proceed from here?

Convert the string to whatever number datatype is appropriate (long if a big number, float/double for decimals etc.) using Long.parseLong(String) or Integer.parseInteger(String) etc. Then you can simply multiply the two numbers.
Example:
String string1 = ".5";//Double in a string
String string2 = "6"; //Integer in a string
double multiplied = Double.parseDouble(string1) * Integer.parseInt(string2) * 3; //.5 * 6 * 3 = 9.0; number form (not string)

Before you can do anything with the number, you have to convert the value to an floating-point value. You can use the following approach:
double num = Double.parseDouble(numberText.getText())
Then you can perform your multiplication.

This might help.
String strNumber = numberText.getText();;
if (strNumber.contains(".")) {
System.out.println(Double.parseDouble(strNumber) * 174);
} else {
System.out.println(Integer.parseInt(strNumber) * 174);
}

Related

Adding two numbers inside a string

This is my code:
String result = "10+23";
int calculatedResult = Integer.parseInt(result);
Log.e(TAG, String.valueOf(calculatedResult);
It keeps giving an error.
Well, you cant convert String result = "10+23"; to an int because you have a + there. What exactly are you trying to do? If you want to take 2 Strings and get their result, then here's the code:
String a = "10";
String b = "23";
int result = Integer.parseInt(a) + Integer.parseInt(b);
//The sum of the two values as a String
String calculatedResult = String.valueOf(result);
Log.i("Tag", calculatedResult); //Outputs 33
It give error because "10+23" is not a number it's contains a the symbol + and the method Integer.parseInt(String s); only convert strings like "23" or "10.5"
So to solve the problem try to convert etch number alone, like that
String number1 = "10";
String number2 = "23";
int calculatedResult = Integer.parseInt(number1)+Integer.parseInt(number2);
Log.e(TAG, String.valueOf(calculatedResult);
for more information and examples about Integer.parseInt(String s); click here

Display Double as string ignoring decimal part when the value is a whole number

What's the simplest way to display a double as String but not showing the decimal part if the double value is a whole number?
For example, If I have the double value 10.0 it would display only 10 (no decimal part), but if I have the double value 10.35 it would display the complete value 10.35.
I would use this approach:
// 1. Make sure to have dot instead of comma as a separator:
DecimalFormatSymbols symbol = new DecimalFormatSymbols(Locale.US);
// 2. Define max number of decimal places:
DecimalFormat df = new DecimalFormat("#.###", symbol);
// 3. Use it:
System.out.println(df.format(yourNumber));
Just use java.text.NumberFormat
Example:
final NumberFormat numberFormat = NumberFormat.getInstance();
System.out.println(numberFormat.format( 10.0d ));
System.out.println(numberFormat.format( 10.35d ));
the output will be:
10
10,35
double one = 1.00;
String stringNumber;
if (one % 1 == 0) {
Integer intOne = (int) one;
stringNumber = intOne.toString();
} else {
stringNumber = String.valueOf(one);
}
This works fine:
System.out.println(getString(4.53)); // 4.53
System.out.println(getString(4.0)); // 4
public String getString(double d){
return (d % 1 == 0) ? String.valueOf((int) d) : String.valueOf(d);
}

Sum 2 string numbers [duplicate]

This question already has answers here:
How can I find the sum of two numbers which are in String variables?
(10 answers)
Closed 4 years ago.
I've looked it up, but couldn't get a real answer to that. So I want to know how to sum up 2 string numbers together.
for example:
String a = "8";
String b = "1";
I want to sum both of them to "9". Is that possible?
Thanks.
edit - that is the code Im trying to use:
String num = Integer.toString(i);
String doubleNumber = Integer.toString(i * i);
int length = doubleNumber.length();
String firstNumber;
String secondNumber;
for (int q = 0; q < length; q++) {
firstNumber = doubleNumber.substring(0, Math.min(doubleNumber.length(), q+1));
secondNumber = doubleNumber.substring(q+1, Math.min(doubleNumber.length(), doubleNumber.length()));
String result = String.valueOf(Integer.parseInt(firstNumber) + Integer.parseInt(secondNumber));
if(num.equals(result)) {
isKaprekar = true;
}
}
edit 2 - I have no idea how, but I opened another class, pasted the same code, and it just magically worked. It makes 0 sense, cause its the same project, everything is the same, but it works now, so I don't care. Thanks everyone for the help!
There is a method called Integer#parseInt(String) which returns an int representation of a given String (if possible):
String a = "8";
String b = "1";
int sum = Integer.parseInt(a) + Integer.parseInt(b);
If you want to change it back to a String, use String#valueOf(int):
String s = String.valueOf(sum);
I'd parse them to ints, add them, and then convert the result back to a string:
String result = String.valueOf(Integer.parseInt(a) + Integer.parseInt(b));
You need to convert both to Integers:
String a = "8";
String b = "1";
int sum = Integer.parseInt(a, 10) + Integer.parseInt(b, 10);
The second argument of Integer.parseInt() is the radix, which tells which number base to use. You can leave this argument out altogether and it will default to using a radix of 10:
int sum = Integer.parseInt(a) + Integer.parseInt(b);
If you want to convert them back to a string, just pass the value into String.valueOf():
String sumString = String.valueOf(sum);
Do this:
String a = "8";
String b = "1";
String sum = String.valueOf(Integer.parseInt(a)
+Integer.parseInt(b));
//printing sum
System.out.println(sum);
Parse the string to int using Integer.parseInt(string)and add them as normal integers.
For example :
String result = String.valueOf(Integer.parseInt(a) + Integer.parseInt(b));
should give you the desired string value as "9"

How to convert a location in Degrees Minutes Seconds represented as a String to Double

My app lets users search a location and one of the queries I got was
"78°14'09"N 15°29'29"E"
Obviously the user wants to go to this location.
First how do I check if this string fits the decimal format correctly. Then how do I convert it to double format?
double latitude = convertToDouble("78°14'09"N")
I searched here on stackoverflow but they are all looking for the opposite: double to decimal.
78°14'09"N 15°29'29"E
First how do I check if this string fits the decimal format correctly. Then how do I convert it to double format?
The string is not in decimal (degrees) format. It is in degrees, minutes, and seconds, which is more or less the opposite of decimal degrees format. I therefore interpret you to mean that you want to test whether the string is in valid D/M/S format, and if so, to convert it to decimal degrees, represented as a pair of doubles.
This is mostly a parsing problem, and regular expressions are often useful for simple parsing problems such as this one. A suitable regular expression can both check the format and capture the numeric parts that you need to extract. Here is one way to create such a pattern:
private final static Pattern DMS_PATTERN = Pattern.compile(
"(-?)([0-9]{1,2})°([0-5]?[0-9])'([0-5]?[0-9])\"([NS])\\s*" +
"(-?)([0-1]?[0-9]{1,2})°([0-5]?[0-9])'([0-5]?[0-9])\"([EW])");
That's a bit dense, I acknowledge. If you are not familiar with regular expressions then this is no place for a complete explanation; the API docs for Pattern provide an overview, and you can find tutorials in many places. If you find that your input matches this pattern, then not only have you verified the format, but you have also parsed out the correct pieces for the conversion to decimal degrees.
The basic formula is decimal = degrees + minutes / 60 + seconds / 3600. You have the additional complication that coordinates' direction from the equator / prime meridian might be expressed either via N/S, E/W or by signed N, E, or by a combination of both. The above pattern accommodates all of those alternatives.
Putting it all together, you might do something like this:
private double toDouble(Matcher m, int offset) {
int sign = "".equals(m.group(1 + offset)) ? 1 : -1;
double degrees = Double.parseDouble(m.group(2 + offset));
double minutes = Double.parseDouble(m.group(3 + offset));
double seconds = Double.parseDouble(m.group(4 + offset));
int direction = "NE".contains(m.group(5 + offset)) ? 1 : -1;
return sign * direction * (degrees + minutes / 60 + seconds / 3600);
}
public double[] convert(String dms) {
Matcher m = DMS_PATTERN.matcher(dms.trim());
if (m.matches()) {
double latitude = toDouble(m, 0);
double longitude = toDouble(m, 5);
if ((Math.abs(latitude) > 90) || (Math.abs(longitude) > 180)) {
throw new NumberFormatException("Invalid latitude or longitude");
}
return new double[] { latitude, longitude };
} else {
throw new NumberFormatException(
"Malformed degrees/minutes/seconds/direction coordinates");
}
}
The convert() method is the main one; it returns the coordinates as an array of two doubles, representing the coordinates in decimal degrees north and east of the intersection of the equator with the prime meridian. Latitudes south of the equator are represented as negative, as are longitudes west of the prime meridian. A NumberFormatException is thrown if the input does not match the pattern, or if the latitude or longitude apparently represented is invalid (the magnitude of the longitude cannot exceed 180°; that of the latitude cannot exceed 90°).
You won't be able to parse that into a double without removing the non number chars but,
String string = "78°14'09"N";
Double number = 0;
try{
number = Double.parseDouble(string);
//do something..
}catch (NumberFormatException e){
//do something.. can't be parsed
}
If you first remove any characters from the string that are not alphanumeric, then something along these lines will work. This code compiles.
public class HelloWorld{
public static void main(String []args){
String input = "78 14'09 N 15 29'29 E".replaceAll("[^A-Za-z0-9]", " ");
String[] array = input.split(" ");
int nDegree = Integer.parseInt(array[0]);
int nMinute = Integer.parseInt(array[1]);
int nSecond = Integer.parseInt(array[2]);
int eDegree = Integer.parseInt(array[4]);
int eMinute = Integer.parseInt(array[5]);
int eSecond = Integer.parseInt(array[6]);
double nDegrees = nDegree + (double) nMinute/60 + (double) nSecond/3600;
double eDegrees = eDegree + (double) eMinute/60 + (double) eSecond/3600;
String nResult = "Decimal = N " + Double.toString(nDegrees).substring(0,10);
String eResult = "Decimal = E " + Double.toString(eDegrees).substring(0,10);
System.out.println(nResult);
System.out.println(eResult);
}
}
Output:
Decimal = N 78.2358333
Decimal = E 15.4913888
The problem is that Java can't store the degrees ° character as part of a String, or internal quotes (the minute character). If you can find a way to remove them from the string before inputting the data, then this will work.
I don't have a solution for handling the degrees symbol, but you could use an escape symbol \" to allow the use of a quotation mark within a string.
So I've used a regex with capturing groups to grab each of the numbers and the N/S/E/W. After capturing each individually it's just a matter of doing a bit of dividing to get the numbers and then formatting them however you'd like. For example I went with 5 digits of precision here.
public static void main(String[] args) {
String coords = "78°14'09N 15°29'29E";
String[] decimalCoords = degreesToDecimal(coords);
System.out.println(decimalCoords[0]);
System.out.println(decimalCoords[1]);
}
public static String[] degreesToDecimal(String degMinSec) {
String[] result = new String[2];
Pattern p = Pattern.compile("(\\d+).*?(\\d+).*?(\\d+).*?([N|S|E|W]).*?(\\d+).*?(\\d+).*?(\\d+).*?([N|S|E|W]).*?");
Matcher m = p.matcher(degMinSec);
if (m.find()) {
int degLat = Integer.parseInt(m.group(1));
int minLat = Integer.parseInt(m.group(2));
int secLat = Integer.parseInt(m.group(3));
String dirLat = m.group(4);
int degLon = Integer.parseInt(m.group(5));
int minLon = Integer.parseInt(m.group(6));
int secLon = Integer.parseInt(m.group(7));
String dirLon = m.group(8);
DecimalFormat formatter = new DecimalFormat("#.#####", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
formatter.setRoundingMode(RoundingMode.DOWN);
result[0] = formatter.format(degLat + minLat / 60.0 + secLat / 3600.0) + " " + dirLat;
result[1] = formatter.format(degLon + minLon / 60.0 + secLon / 3600.0) + " " + dirLon;
}
return result;
}
There is no error handling here, it's just a basic example of how you could make this work with your input.

Remove unnecessary decimals

I got this code that fetches floats from a database.
for (int i = 0; i < ingredient.size() ; i++) {
Ingredient ing = (Ingredient) ingredient.get(i);
ingredients += String.valueOf(ing.getAmount()) + " " +
ing.getUnit() + " " + ing.getIngredient() + "\n";
}
The database is written in REAL values as some of them is 1.5, 2.5, 1.4 etc. But we also have these whole numbers without the need of a decimal, such as 1, 4, 10 etc.
The problem is that the database table needs to be in REAL value, which gives us no choice but to give all the values one decimal, no matter if it's needed or not.
So we'll end up with values like:
1.0
1.5
2.3
20.0
5.0
My question is: How do we remove the unnecessary decimals, but keep the ones that need it?
One very simple way to remove these would be to strip the characters using StringUtils.
String displayValue = String.valueOf(ing.getAmount());
displayValue = StringUtils.stripEnd(displayValue, ".0");
For an input of "1.0", "1" will be returned.
A more technical approach would be to use the modulus operator %
For example:
if(value%1 == 0){ //1 divides into number perfectly, there is no decimal
//cast value to integer or another non decimal variable
} else {
//use existing value as it contains a decimal
}
How about this (does't require any fancy things like StringUtils)?
String s = String.valueOf(1.0);
System.out.println(s);
/* Make this block as a function and return an int */
String ss = " ";
if (s.charAt(s.length()-2) == '.' && s.charAt(s.length()-1) == '0'){
ss = s.substring(0,s.length()-2);
System.out.println(ss);
}
/**************************************************/
int converted = Integer.parseInt(ss);
System.out.println(converted);
}
If you want to make it a function block, you can.
You can check it working on IDEONE - http://ideone.com/udJv8M
Check the float values with modulo. If 0 is returned it is an Integer. Here is an example with the numbers you have mentioned:
List<Float> values = new ArrayList<Float>();
values.add(new Float(1.0f));
values.add(new Float(1.5f));
values.add(new Float(2.3f));
values.add(new Float(20.0f));
values.add(new Float(5.0f));
List<String> strValues = new ArrayList<String>();
for(Float value : values)
{
String strValue = "";
if(value % 1 == 0)
{
Integer intValue = value.intValue();
strValue = intValue.toString();
strValues.add(strValue);
}
else
{
strValue = value.toString();
strValues.add(strValue);
}
System.out.println(strValue);
}
You can use a custom DecimalFormat pattern:
public static String customFormat(String pattern, double value) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
return myFormatter.format(value);
}
Then a pattern of # defines places holders for optional digits, so #.### will give up to 3 digits where necessary only.
for (int i = 0; i < ingredient.size() ; i++) {
Ingredient ing = (Ingredient) ingredient.get(i);
ingredients += customFormat("#.###", ing.getAmount()) +
" " + ing.getUnit() + " " + ing.getIngredient() + "\n";
}
So don't convert your data to a String except for display only. Real numbers can represent both integers and floating point numbers using the same data type. Plus if you ever needed to do any math on your numbers you can't use Strings to do that. If you convert your numbers from the database directly to String before storing them into Ingredient then you've screwed yourself later on if you want to do calculations on those numbers. (Say you wanted to add a feature to double a recipe and have all of the quantities change for the user). Under your current plan you're preventing yourself from doing something like that because you're overly focused on the display of that number.
Instead just create a method on Ingredient to convert your numbers using String.format(). Like so:
public class Ingredient {
private double amount;
private String name;
public String asDecimal() {
return String.format("%.1f", amount);
}
public String asInteger() {
return String.format("%.0f", amount);
}
public String asFraction() {
// exercise left to the reader
}
}
You could even add a function that converts decimals to fractional amounts to make it easier to display things chiefs might understand vs decimals which are harder. Bear in mind String.format() will round floating point amounts (0.5 -> 1 using as Integer).
Convert your String returned from ing.getAmount() to a Float object, then use the modulo function to determine whether your value is an exact multiple of 1 (ie no decimal places). If so, convert your Float object to an int, which will concatenate the decimals.
Float f = Float.valueOf(ing.getAmount());
if(f%1 == 0) {
// Use f.intValue() to concatenate your decimals.
ingredients +=String.valueOf(f.intValue() + " " + ing.getUnit() + " " + ing.getIngredient() + "\n";
}
else {
ingredients +=String.valueOf(ing.getAmount()) + " " + ing.getUnit() + " " + ing.getIngredient() + "\n";
}
I hope this helps.

Categories

Resources