I get a double value (eg. -3.1234) which contains a value in decimals (0.1234 in this case). I want to remove the value in decimal value (in this case I wanted the value -3). How do I do it? I know how to remove the decimal if the decimal only has 0, but in this case I don't have the decimal value as 0.
Anyways here is the code for that:
DecimalFormat format = new DecimalFormat();
format.setDecimalSeparatorAlwaysShown(false);
Double asdf = 2.0;
Double asdf2 = 2.11;
Double asdf3 = 2000.11;
System.out.println( format.format(asdf) );
System.out.println( format.format(asdf2) );
System.out.println( format.format(asdf3) );
/*
prints-:
2
2.11
2000.11
*/
If you just want to print it :
String val = String.format("%.0f", 2.11)
// val == "2"
If you want to keep the double type but without decimals :
double val = Math.floor(2.11);
// val == 2.000
If you don't care about type you can cast the double into int :
int val = (int) 2.11;
// val == 2
//double as object
int val = myDouble.integerValue();
You can simply use the intValue() method of Double to get the integer part.
You can cast it to int
int i=(int)2.12
System.out.println(i); // Prints 2
Round up decimal value & convert it into integer;
Integer intValue = Integer.valueOf((int) Math.round(doubleValue)));
http://www.studytonight.com/java/type-casting-in-java check out type conversion in java
double asdf2 = 2.11;
int i = (int)asdf2;
System.out.println(asdf2);
System.out.println(i);
Output:
2.11`
2
Related
I a working with Strings with the format I've mentioned such as "5:4" and I need to get their value (for example "5:4" equals 1.25).
A simple .toDouble(), what would be the best approach
You could Iterable.reduce() :
println(
a.split(":").map { it.toDouble() }.reduce { a, b -> a / b }
) // 1.25
A method with plain Kotlin using the String.split() method could look like this:
// INPUT
val ratio = "5:4" // can be "5/4" as well
// splits given string into a list and then cast it's members into Double
val items : List<Double> = (ratio.split(":", "/")).map { it.toDouble() } // [5, 4]
var result = 0.0
// calculate the ratio
if (items.size == 2 && items[1] != 0.0)
result = items[0] / items[1]
println(result) // 1.25
String a="5:4";
a= a.replaceAll(":", "/");
float result = new Expression(a).eval();
I have a string named namely "-10.00","-100.00","-1000.00". I want to get value like "10","100","1000" from that string. I have tried to get substring but did not able to get.
code i have tried
String amount = "-10.00";
String trimwalletBalance = amount.substring(0, amount.indexOf('.'));
From above i only get "-10".
String trimwalletBalance = amount.substring(1, amoun.indexOf("."));
Its very simple.
Do it like String trimwalletBalance = amount.substring(1, amount.indexOf('.'));
Instead of position 0, You should get substring from position 1
Convert it into integer and then name it positive:
String amount = "-10.00";
int amountInt = (int) Double.parseDouble(amount);
if(amountInt<0)amountInt*=-1;
Try
String amount = "-10.00";
int value = (int) Double.parseDouble(amount);
if(value < 0) value *= -1;
//value will be 10
OR
String text = amount.substring(1, amount.indexOf('.'));
I have two variables with datatype double, when i multiply those variables they return result in scientific form but my requirement is to display result in normal human readable form.
For Example:
when i multiply 9854795 and 8.9 it returns result as 8.77076755E7 instead of 87707675.5
here is my function for calculating values:
private void calculatingTotalPaymentAmount() {
if (editTextBookingQuantity.getText().toString().equals(""))
{
editTextBookingQuantity.setError("Enter Booking Quantity to calculate Total Payment Amount");
return;
} else if (editTextRatePerBrick.getText().toString().equals(""))
{
editTextRatePerBrick.setError("Enter Rate Per Brick to calculate Total Payment Amount");
return;
} else {
//MathContext mc = new MathContext(4); // 4 precision
final double catchBookingQtyDoubleForm = Double.parseDouble(editTextBookingQuantity.getText().toString());
final double catchRatePerBrickDoubleForm = Double.parseDouble(editTextRatePerBrick.getText().toString().trim());
final double totalPaymentAmount = (catchBookingQtyDoubleForm * catchRatePerBrickDoubleForm);
//bg3 = bg1.multiply(bg2, mc);
//BigDecimal newValue = totalPaymentAmount.setScale(0, RoundingMode.DOWN);
editTextTotalPaymentAmount.setText(""+totalPaymentAmount);
}
}
Log.d("tag", "" + new BigDecimal(catchBookingQtyDoubleForm * catchRatePerBrickDoubleForm));
I have an EditText field where the user can enter his weight in Kilogram, i.e. 11.7. I want to store that in the database as gramms, i.e. 11700.
How do I convert the String "11.7" to the Integer 11700?
To get the value from an EditText use http://developer.android.com/reference/android/widget/EditText.html#getText()
String userInput = editText.getText().toString();
To convert a String into a double use the code from #govindpatel http://developer.android.com/reference/java/lang/Double.html#parseDouble(java.lang.String)
try {
double kg = Double.parseDouble(userInput)
}
catch (NumberFormatException nfe) {
editText.setError(R.string.invalid_double); // Or whatever you want to show the user
}
To convert from KG to g:
long gramms = Math.round(kg * 1000);
You could replace the double and long with float and int if you know you don't need the precision or range of the larger variables.
you have to parse it to int,long or double.
I think In your case you can do this
double grams = Double.parseDouble("11.7") * 1000;
double variable_name = Double.parseDouble(string_name) * number_you_want_to_multiply_with;
and this will give a double value. So you can convert that to integer, long or keep as it is in your db.
to convert double to long you can do something like this:
long value = (long)(grams);
Hope this helps you,
I'm not sure what it has to do with Android?
int grams = (int)(kg * 1000);
To get text from EditText
EditText mEdit = (EditText)findViewById(R.id.edittext);
double kg = Double.parseDouble(mEdit.getText().toString());
I'm trying to get it to if a user doesn't enter a value in the EditText boxes, the initial value is set to 0 (to prevent the crash error NumberFormatException Invalid int: "") which is thrown assuming because there is no integer value to read, since the user didn't input one in this case.
I've tried a number of things most recently this:
String boozeAmount = boozeConsumed.getText().toString();
if (boozeAmount == "" || boozeAmount == null){
boozeConsumed.setText("0");
boozeAmount = boozeConsumed.getText().toString();
}
int boozeOz = Integer.parseInt(boozeAmount) * 12;
double beerCalc = boozeOz * 4 * 0.075;
But it seems to still throw the same error, not sure why the int values aren't being set to 0?
Throwing error on
int boozeOz = Integer.parseInt(boozeAmount) * 12;
if (boozeAmount == "" || boozeAmount == null){
It can be easily deduced from your explanation that this particular if statement is returning true, that's why your string value is not being set to "0".
Strings in Java are not primitive, i.e they cannot be compared with the comparator ==.
You need to use the method equals to compare strings, as in boozeAmount.equals("").
Apache Commons has a StringUtils utility that can check if strings are null or empty.
Check out isEmpty and isBlank.
you dont compare strings with == you compare it with .equals()
Change it to:
if (boozeAmount.equals("") || boozeAmount == null)
Although it's probably safest to also do:
if (...)
{
// just set it to zero and skip even trying to parse
}
else
{
// do the actual parsing
}
Whenever you are fetching a string value from the EditText always trim that variable to avoid any white spaces from EditText.
String boozeAmount = boozeConsumed.getText().toString().trim(); // apply Trim
// Always compare strings with `equals()` method in Java & Android
if ( boozeAmount.equals( "" ) || boozeAmount == null )
{
boozeConsumed.setText("0");
boozeAmount = boozeConsumed.getText().toString();
}
int boozeOz = Integer.parseInt(boozeAmount) * 12;
double beerCalc = boozeOz * 4 * 0.075;
You could check if it's blank and then fill it with 0 and then get the input.
Also, always compare string values with .equals and use .trim() to get rid of whitespace so that it's recognized as invalid input as well.
if (boozeConsumed.getText().toString().trim().equals("")) {
// if (boozeConsumed.length() == 0) { // doesn't consider spaces though
boozeConsumed.setText("0");
}
String boozeAmount = boozeConsumed.getText().toString();
int boozeOz = Integer.parseInt(boozeAmount) * 12;
double beerCalc = boozeOz * 4 * 0.075;
Or just do this, because you don't need to parse it to an integer if you know there's nothing there:
String boozeAmount = boozeConsumed.getText().toString();
int boozeOz = 0;
double beerCalc = 0;
if (boozeAmount.trim().equals("") || boozeAmount == null){
boozeConsumed.setText("0");
boozeAmount = boozeConsumed.getText().toString();
} else {
// only parse it if there's something there
boozeOz = Integer.parseInt(boozeAmount) * 12;
beerCalc = boozeOz * 4 * 0.075;
}