How to convert double to int in Android? [duplicate] - android

This question already has answers here:
Converting double to integer in Java
(3 answers)
Closed 6 years ago.
I just wants to convert from double to int in my UI i am rendering as a double but for the backend i want convert to integer.
Double d = 45.56;
OutPut = 4556;
Please can anybody tell me how to get the value in this format.

Try this way, Courtesy
double d = 45.56;
int i = (int) d;
For better info you can visit converting double to integer in java

If you just want to convert the Double to int,
Double D = 45.56;
int i = Integer.valueOf(D.intValue());
//here i becomes 45
But if you want to remove all decimal numbers and count the whole value,
//first convert the Double to String
double D = 45.56;
String s = String.valueOf(D);
// remove all . (dots) from the String
String str = str.replace(".", "");
//Convert the string back to int
int i = Integer.parseInt(str);
// here i becomes 4556

You are using the Double as object(Wrapper for type double). You need to fist convert it in to string and then int.
Double d=4.5;
int i = Integer.parseInt(d.toString());
If you want it in the Integer Object Wrapper then can be written as
Integer i = Integer.parseInt(d.toString());
EDIT
If you want to get the desired result -
You can go like this-
Double d = 4.5;
double tempD = d;
int tempI = (int) tempD * 100;
//Integer i = tempI;

try this code
double d = 45.56;
String temp = String.valueOf(d);
if (temp .contains(".")) {
temp = temp .replaceAll(".","");
}
// After if you want to convert to integer then
int output = Integer.parseInt(temp);

Related

Android dont print ARGB color like #c01c2112

Does Android not supporting printing the color like #c01c2112 with the format ARGB? It display error because of invalid color.
This part of my code is Store 1 and 0 into the arraylist.
ArrayList<String>arrayList = new ArrayList<>();
for(int a = 0; a < bitmap1.getWidth(); a++){
for(int b = 0; b < bitmap1.getHeight(); b++){
String a1 = String.valueOf(arrayInput1[a][b]);
String a2 = String.valueOf(arrayInput2[a][b]);
String a3 = String.valueOf(arrayInput3[a][b]);
String a4 = String.valueOf(arrayInput4[a][b]);
String a5 = String.valueOf(arrayInput5[a][b]);
String a6 = String.valueOf(arrayInput6[a][b]);
String a7 = String.valueOf(arrayInput7[a][b]);
String a8 = String.valueOf(arrayInput8[a][b]);
arrayList.add(a1+a2+a3+a4+a5+a6+a7+a8);
// Store 1110001 into ArrayList
}
}//End of nested For
Then here is the part to pass the data to an array.
String [] hexArrayRed = new String[arrayList.size()];
arrayList.toArray(hexArrayRed);
Then I input myself the #ff and the 0000 and combine with the data as I convert the data to hexadecimal value type. It is working fine here.
for(int a = 0; a < hexArrayRed.length; a++){
int dec = Integer.parseInt(String.valueOf(arrayList.get(a)),2);
String hexString = Integer.toString(dec, 16);
String alpha = "#ff";
String behind = "0000";
hexArrayRed[a] = alpha+hexString+behind;
/*
Red Hexadecimal Value --> #ff _ _ 0000
*/
}
Then there is the problem.
QRCodeWriter qwRed = new QRCodeWriter();
try {
HashMap<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.MARGIN, 2);
BitMatrix matrix = qwRed.encode(finalText,
BarcodeFormat.QR_CODE,
bitmap1.getWidth(),
bitmap1.getHeight(),
hints);
//START OF RED
final Bitmap newBitmapRed = Bitmap.createBitmap(
bitmap1.getWidth(),
bitmap1.getHeight(),
Bitmap.Config.ARGB_8888
);
int counter1 = 0;
for (int a = 0; a < bitmap1.getWidth(); a++) {
for (int b = 0; b < bitmap1.getHeight(); b++) {
//int c = 0;
int[] color = new int[hexArrayRed.length];
color[counter1] = Color.parseColor(hexArrayRed[counter1]); //Error is right here
int d = matrix.get(a,b)? color[counter1]: Color.WHITE;
newBitmapRed.setPixel(a,b,d);
counter1++;
}
}
//END OF RED
Then I get the error of printing the unknown color.
Process: kopilim.scs.prototyping, PID: 9890
java.lang.IllegalArgumentException: Unknown color
Is it the Android dont support color like #f212cc12 some sort like this the ARGB color?
Your code of converting from binary to decimal to hex works fine, except for one tiny part.
The problem is related to this part of your code:
String hexString = Integer.toString(dec, 16);
The problem with using Integer.toString() is that it'll give you the integer as a String, without the extra 0 padding.
What I mean by this is, for example: if your binary String was 00000111. Using Integer.parseInt("00000111", 2); would give you a decimal int of 7.
Finally, using String hexString = Integer.toString(7, 16); would give you a String of "7".
Therefore, when you plug that value into your hexArrayRed[a], instead of plugging it in as #AARRGGBB, you're plugging it in as #AARGGBB which is an improper format.
So to fix this, you simply have to check the length of hexString to see if it only has a size of 1. If it is, append an extra 0 to the front of it when you create your full hex string.

Rounding to two decimal places in Android

Should be simple I know but I cant find an answer anywhere. I'm trying to round up to two decimal places, so if my answer is 164.9835 I'd like the answer to be displayed as 164.99. But what I have so far is rounding it to 164.98 for some reason.
Any help much appreciated.
double number1 = Double.parseDouble(num1.getText().toString());
double number2 = Double.parseDouble(num2.getText().toString());
double number3 = Double.parseDouble(num3.getText().toString());
double number4 = Double.parseDouble(num4.getText().toString());
double sum = (((number1 * number2)/1000)*0.5)*(number3 - number4);
total.setText (String.format("£%s", new java.text.DecimalFormat("##.##").format(sum)));
If you want to round up you can use this method
cantDecimal = 2;
number = 164.9835
public static double aroundUp(double number, int canDecimal) {
int cifras = (int) Math.pow(10, canDecimal);
return Math.ceil(number * cifras) / cifras;
}
return = 164.99
Extra: Ceil Method in Math.
The method ceil gives the smallest integer that is greater than or equal to the argument.

Why I can not see the double value in a textView

Why I can not see the double value in a textView?
textView = (TextView) findViewById(R.id.textView);
double x = 5/2;
textView.setText(String.valueOf(x)); // I see this result as 2.0 and not as the 2.5
In Android TextView, you can use in that way,
Use Double.toString:
result = number1/number2
String stringdouble= Double.toString(result);
textview1.setText(stringdouble));
or you can use the NumberFormat:
Double result = number1/number2;
NumberFormat nm = NumberFormat.getNumberInstance();
textview1.setText(nm.format(result));
To force for 3 units precision:
private static DecimalFormat REAL_FORMATTER = new DecimalFormat("0.###");
textview1.setText(REAL_FORMATTER.format(result));
You are seeing 2.0 because 5/2 is integer division. Change the line to double x = 5.0/2; or similar.
See this question for more.
This should work double x = ((double) 5) /2.

how can i reduce the digits after the decimal point?

private void findLatLongDistance(double prelat,double prelon,double lat,double lon) {
// TODO Auto-generated method stub
try{
double prelatval=prelat;
double prelongval=prelon;
double curlat=lat;
double curlon=lon;
Log.w("inside finalatlon...........................","the daya");
if(prelatval>0.0 && prelongval>0.0 && lat>0.0 && lat>0.0 && gpsdataElements.Speed>0.0){
float distance2 = getDistance(prelatval,prelongval,curlat,curlon);
odometer_sum= (distance2/1000 );
// for maximum value after decimal
//df.setMaximumFractionDigits(0);
//rounding the km digits after decimal
Math.round(distance2);
//for minimum distance after decimal
df.setMinimumFractionDigits(2);
df.format(odometer_sum);
gpsdataElements.Distance = gpsdataElements.Distance + odometer_sum;
}
}catch(Exception e){
e.printStackTrace();
}
}
here is my code. I want distance(i.e km)value digits after decimal is two digits. Example i want km value in 1.54km not like 1.4568923km. How to get like this.I tried a lot for that but i din't got any possible solution. Any one know please help me.
In more simple ways you can do this by using this :
double roundOff = Math.round(yourValue * 100.0) / 100.0;
Otherwise you can also do this as
String.format("%.2f", d)
DecimalFormat formatter = new DecimalFormat(".##");
String s = formatter.format(value);
use this code to format text in two digits after decimal.
double i2=i/60000;
tv.setText(new DecimalFormat("##.##").format(i2));
double roundof = Math.round(a * 100.0) / 100.0;
output:roundoff(eg:12).oo
12.00
Something like this :
String.format("%.2f", distance);
Make function like this pass the value as per you requirment and return value as per your requirment first function will take float value and after decimal it put 3 value as per argument if you want to change decimal value then you can change 3,2,4 etc... Second function will take String value and round it in 3 decimal point:
public static BigDecimal round(float d) {
BigDecimal bd = new BigDecimal(Float.toString(d));
bd = bd.setScale(3, BigDecimal.ROUND_HALF_UP);
return bd;
}
public static BigDecimal round(String d) {
BigDecimal bd = new BigDecimal(Float.parseFloat(d));
bd = bd.setScale(3, BigDecimal.ROUND_HALF_UP);
return bd;
}

Display decimals with a textview

Hi i want make so the TextView level can put out decimal but i don'ty know how to do that any one got an idea? NOw it only puts out 1 but i want it to put out 1.80. :)
public class Main extends Activity {
int counter;
EditText weight, hours;
TextView amount, level;
Button calcuate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter = 0;
weight = (EditText) findViewById(R.id.weight);
hours = (EditText) findViewById(R.id.hours);
amount = (TextView) findViewById(R.id.amount);
level = (TextView) findViewById(R.id.alcohol_level);
calcuate = (Button) findViewById(R.id.calcuate);
final String widmark = getResources().getString(
R.string.widmark);
final String hundra = getResources().getString(
R.string.hundra);
final String cl = getResources().getString(
R.string.cl);
calcuate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer wid, mgs;
String w = weight.getText().toString();
String h = hours.getText().toString();
wid = Integer.parseInt(w) * Integer.parseInt(widmark) / Integer.parseInt(hundra);
mgs = Integer.parseInt(cl) / Integer.parseInt(wid.toString()) / Integer.parseInt(hundra);
level.setText(mgs.toString());
}
});
}
}
Your mgs variable is a Integer object. Set it to type float to have decimal places be displayed.
float mgs = Integer.parseInt(cl) / Integer.parseInt(wid.toString()) / Integer.parseInt(hundra);
I hope this helps.
int division will only produce int's. If you want your output to be of float or double type, you must use double or float division.
Double mgs;
mgs = Double.parseDouble(cl) / Double.parseDouble(wid.toString()) / Double.parseDouble(hundra);
Note that not all variables considered in the expression need to be double's, only one of them does.
Another thing that is noteworthy here is whether or not you want two decimal places (assuming a currency here). By default, Java/Android will only spit out as many decimal places as necessary. 1.80 will display as 1.8. To alleviate this, you should use a NumberFormat (specifically, use NumberFormat.getCurrencyInstance()) so that you can specify that you want the number of decimals for your default Locale's currency.

Categories

Resources