How to convert integer to decimal format in Java (Android Studio)? - java

I am trying to convert my two answers text1 and text2 into a decimal format. How is this possible?
int number1, number2, answer, answer2;
EditText edit1 = (EditText)findViewById(R.id.aNum);
EditText edit2 = (EditText)findViewById(R.id.bNum);
TextView text1 = (TextView)findViewById(R.id.answerNum);
TextView text2 = (TextView)findViewById(R.id.answerNum2);
number1 = Integer.parseInt(edit1.getText().toString());
number2 = Integer.parseInt(edit2.getText().toString());
answer = (number2 / (number1 * 1000)) * 60;
answer2 = answer/60;
text1.setText(Integer.toString(answer));
text2.setText(Integer.toString(answer2));

The first issue is the ints are whole numbers, i.e. no decimal places so if you had:
int a = 3;
int b = 2;
int result = a / b;
The result would be 1 not 1.5. If you need to preserve the floating point values cast them to doubles or floats instead. Then you can then use String.format to display the value correctly:
text1.setText(String.format("%.2f",answer));
Which will display the answer to two decimal places.

You can use BigDecimal:
i.e.:
new BigDecimal(theInputString);

Use float variable type instead of int, and Float class instead of Integer class:
float number1, number2, answer, answer2
EditText edit1 = (EditText)findViewById(R.id.aNum);
EditText edit2 = (EditText)findViewById(R.id.bNum);
TextView text1 = (TextView)findViewById(R.id.answerNum);
TextView text2 = (TextView)findViewById(R.id.answerNum2);
number1 = Float.parseFloat(edit1.getText().toString());
number2 = Float.parseFloat(edit1.getText().toString());
answer = (number2 / (number1 * 1000)) * 60;
answer2 = answer / 60;
text1.setText(Float.toString(answer));
text2.setText(Float.toString(answer2));

Related

How to retrieve decimal value from Integer?

I'm trying to calculate the average based on user input. Now I've got the basics working, but I am only getting whole numbers as result. I want decimal numbers like 5.5
Any explanation is welcome!
final TextView averageView = findViewById(R.id.averageView);
final String averageText = getString(R.string.average);
final Button calculateButton = findViewById(R.id.calculateAverageButton);
calaculateButton.setOnClickListener(new View.onClickListener() {
#SupressLint("SetTextI18n")
public void onClick(View v) {
int grade[] = {Integer.parseInt(((EditText) findViewById(R.id.grade1)).getText().toString());
int weight[] = {Integer.parseInt(((EditText) findViewById(R.id.weight1)).getText().toString());
int weightTotal = weight[0];
int sum = grade[0] * weight[0]
int average = sum / weightTotal
averageView.setText(averageText + Integer.toString(average));
EDIT:
I have experimented with a answer and got a solution for my problem.
final TextView averageView = findViewById(R.id.averageView);
final String averageText = getString(R.string.average);
final Button calculateButton = findViewById(R.id.calculateAverageButton);
calaculateButton.setOnClickListener(new View.onClickListener() {
#SupressLint("SetTextI18n")
public void onClick(View v) {
double grade[] = {Double.parseDouble(((EditText) findViewById(R.id.grade1)).getText().toString());
double weight[] = {Double.parseDouble(((EditText) findViewById(R.id.weight1)).getText().toString());
double weightTotal = weight[0];
double sum = grade[0] * weight[0]
double average = sum / weightTotal
averageView.setText(averageText + " " + Double.toString(average));
Ok You can do it like this
final TextView averageView = findViewById(R.id.averageView);
final String averageText = getString(R.string.average);
final Button calculateButton = findViewById(R.id.calculateAverageButton);
calaculateButton.setOnClickListener(new View.onClickListener() {
#SupressLint("SetTextI18n")
public void onClick(View v) {
int grade = {Integer.parseInt(((EditText)
findViewById(R.id.grade1)).getText().toString());
int weight = {Integer.parseInt(((EditText)
findViewById(R.id.weight1)).getText().toString());
double sum = grade * weight
double average = sum / weight
averageView.setText(averageText +" "+ average);
The division operator / means integer division if there is an integer
on both sides of it. If one or two sides has a floating point number,
then it means floating point division. The result of integer division
is always an integer. Integer division determines how many times one
integer goes into another. The remainder after integer division is
simply dropped, no matter how big it is.
Change the type of variable average to float and typecast one of the sum or weight to float:
float average = (float)sum / weightTotal;
Also change Integer.toString(average) to Float.toString(average)
You are getting integers because you are only using integers !!.
That's normal, If you like average as decimal you have to declare it as Float or Double instead of int.
Note that even if you use such casting (Float.parseFloat....) it wont work because the variable average can only hold integers.
float x = (float) y / z
text.setText("your avarage is : " + x );
also you should use try/catch while get data from edittext for convert Integer. otherwise you can get crash

Decimal place on a Double TextView

Hi I'm new to Java Programming and I need some help.
I'm making a calculation app and I'm struggling with how to use decimals with textview in my results page. Could anyone help
My code:
double result1 = num1 + num2;
double result2 = num1 / num2;
double result3 = num1 * num2;
setContentView(R.layout.activity_result);
TextView plusResult = (TextView)findViewById(R.id.plus_result);
plusResult.setText(Double.toString(result1));
TextView divResult = (TextView)findViewById(R.id.div_result);
divResult.setText(Double.toString(result2));
TextView timesResult = (TextView)findViewById(R.id.times_result);
timesResult.setText(Double.toString(result3));
break;
Based on your comments, you want to limit the answer to two decimal places. The following change does this:
double result1 = Math.round((num1 + num2) * 100.0) / 100.0;
double result2 = Math.round((num1 / num2) * 100.0) / 100.0;
double result3 = Math.round((num1 * num2) * 100.0) / 100.0;
It would be better to add a helper function to round if you do this in many places throughout your application.
If you want to round to two decimal places, you could create a method like so:
private double round(double value){
return (Math.round(value * 100.0) / 100.0);
}
Multiply it by 100, round to a whole number, then divide by 100 to get exactly 2 decimal places. If you need more or less decimal places, you can change the 100's to different powers of 10.

Setting 2 decimal places in double value in Java

I get the values from the j table. I want to show cost in 2 decimal places and qty in no decimal places.
Currently both outputs one decimal place(123.0)
How to fix this;
DecimalFormat df= new DecimalFormat("0.00");
int i = tableSale.getRowCount();
String id = (String) tableSale.getValueAt(i-1, 0);
String name = (String) tableSale.getValueAt(i-1, 1);
double dcost = (double) tableSale.getValueAt(i-1, 2);
double cst=Double.valueOf(df.format(dcost));//setting 2 decimal places
String cost = String.valueOf(cst);//converting double to string
double dqty = (double) tableSale.getValueAt(i-1, 3);
DecimalFormat dd=new DecimalFormat("0");
double qt = Double.valueOf(dd.format(dqty));
String qty = String.valueOf(dqty);//converting double to string
double ditemDiscount = (double) tableSale.getValueAt(i-1, 4);
String itemDiscount = String.valueOf(ditemDiscount);//converting double to string
double dgrossTotal = (double) tableSale.getValueAt(i-1, 5);
double gTotal=Double.valueOf(df.format(dgrossTotal));//setting 2 decimal places
String grossTotal = String.valueOf(gTotal);//converting double to string
I think you can use this:
double dcost = (double) tableSale.getValueAt(i-1, 2);
String text = new DecimalFormat("##.##").format(dcost);
For the same with the rest double values.
Hope this help!
double d;
System.out.printf(".2f",d);
For costs I would advise against double. Use BigDecimal instead.
As for the formatting:
String.format("%.2d", dcost); and String.format("%.0d", qty); can be used.
try
String.format("%.2f", 123.0) //for two decimal point.
and
String.format("%.0f", 123.0)// for no decimal point.
output:
123.00
123
If you want to round to 2 decimal places you can use this function.
double dcost = round2(tableSale.getValueAt(i-1, 2));
This avoids the overhead of formatting a string just so you can parse it.
private static final double WHOLE_NUMBER = 1L << 53;
public static double round2(double d) {
final double factor = 1e2;
return d > WHOLE_NUMBER || d < -WHOLE_NUMBER ? d :
(long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor;
}
You can adjust the factor to taste.

Convert "0.25000%" to double in java

Please help to convert the string value ("0.25000%") to double value.
0.25000% = 0.0025 (need to get this value as double)
String num = "0.25000%";
double d = Double.parseDouble(num);//does not work
You can try this
String num = "0.25000%";
double d = Double.parseDouble(num.replace("%","")); // remove %
System.out.println(d);
Out put:
0.25
For your edit:
You can divide final answer by 100
System.out.println(d/100);
Now out put:
0.0025
String num = "0.25000%";
BigDecimal d = new BigDecimal(num .trim().replace("%","")).divide(BigDecimal.valueOf(100));//no problem BigDecimal
this can convert for decimal.
Remove the % character and divide by 100
String num = "0.25000%";
double d = Double.parseDouble(num.replace("%","")) / 100;

split float in Java Android

I have a number like 2.75. I want to split this number into two other floats. Here is an example of what I am searching for:
value = 2.75
value2 = 2.0
value3 = 0.75
I need them in my algorithm, so how could I implement this? I found split() but it returns string. I need floats or integer at least.
You could cast
float value = 2.75f;
int valueTruncated = (int) value;
float value2 = valueTruncated;
float value3 = value - value2;
You can also try this
double value = 2.75;
double fraction=value%1;//Give you 0.75 as remainder
int integer=(int)value;//give you 2 fraction part will be removed
NOTE:
As result may very in fraction due to use of double.You better use
float fraction=(float) (value%1);
if fractional part is big.
Another option is to use split():
double value = 2.75;
/* This won't work */// String[] strValues = String.valueOf(value).split(".");
String[] strValues = String.valueOf(value).split("\\.");
double val1 = Double.parseDouble(strValues[0]); // 2.0
double val2 = Double.parseDouble(strValues[1]); // 0.75
if the input is 59.38
result is
n1 = 59
n2 = 38
this is what I came up with:
int n1, n2 = 0;
Scanner scan = new Scanner(System.in);
double input = scan.nextDouble();
n1 = (int) input;
n2 = (int) Math.round((input % 1) * 100);

Categories