Rounding up decimal in EditText - android

I'm trying to figure out how to round up the total to two decimal places. The total is an EditText. I can't get it to narrow down to just two decimal places. What wrong with it? Thanks for your help.
public void macro() {
caloriesTotal = Double.parseDouble(calories.getText().toString());
total = (caloriesTotal * .20)/9;
DecimalFormat round = new DecimalFormat ("###.##");
round.format(total);
carbsTotal = (caloriesTotal * .40)/4;
proteinTotal = (caloriesTotal * .40)/4;
fat.setText(Double.toString(total));
carbs.setText(Double.toString(carbsTotal));
protein.setText(Double.toString(proteinTotal));
}

Try this.
fat.setText(Double.valueOf(round.format(total)));
When you convert any number upto N number of decimal digit then you need to store that value in any variable or directly show like as above i mentioned.

Simply format() should do for you,
DecimalFormat round = new DecimalFormat ("###.##");
String formatted = round.format(double_value);
fat.setText(formatted);

You can use String.format("%.2f", d), your double will be rounded

Related

unable to get the 2 values after decimals but getting zero

Hi friends I want to get two values after decimal,but in my I am getting 0 after the decimal. this is my code below.
if (!ed.getText().toString().equals("")) {
if (rb1.isChecked()) {
int input = Integer.valueOf(ed.getText().toString());
double out = input / 24;
out = (double)Math.round(out * 100)/100;
Intent m = new Intent(Page.this,MActivity.class);
m.putDoubleExtra("res", out);
startActivity(m);
I referred these sites also: Android : How to get just two digit after the point in decimal value ? dont want to trunc the value
Java : how do I get the part after the decimal point?
and I tried the code below also but it getting 0 after decimal.
DecimalFormat newFormat = new DecimalFormat("#.##");
double twoDecimal = Double.valueOf(newFormat.format(d))
Please help me new to coding. Thanks in advance.
Since input and 24 are integers, when you divide it, it still produces int. Only then it is converted to double.
One way to solve this: double out = input / 24.0;
DecimalFormat newFormat = new DecimalFormat("#.00");
double twoDecimal = Double.valueOf(newFormat.format(d))
In your code i found is
out = (double)Math.round(out * 100.0)/100.0;

change format of double like ***.***,**

I have double amount. Let amount to be 500000.12. I want to set value of the amount to TextView like this format 500,000.12 (where 12 is cents , 500,000 is dollars).
I wrote this function and it works
private String getAmountAsString(double amount) {
double integralPart = amount % 1;
int fractionalPart = (int) (amount - integralPart);
int integral = (int) integralPart * 100;
String strFractional = String.format("%,d", fractionalPart);
String strAmount = (strFractional + "." + String.valueOf(integral));
return strAmount;
}
But I think that there can be some easy and good way of doing this with java native functions. Can anybody help to find functions or some better way?
various Locale can be used to format float, double etc. You can use:
String.format(Locale.<Your Locale>, "%1$,.2f", myDouble);
Here .2f represents how many digits you want after decimal. If you are not specifying any locale it will use the default locale.
In String class this method is overloaded as:
format(String format, Object... args)
&
format(Locale l, String format, Object... args)
For more info have a look: Link1 , Link2 and Link3
Therefore NumberFormats are used. They are good to handle local differents for different countries.
//define a local, gets automated if a point or comma is correct in this Country.
NumberFormat anotherFormat = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat anotherDFormat = (DecimalFormat) anotherFormat;
anotherDFormat.applyPattern("#.00");//set the number of digits afer the point
anotherDFormat.setGroupingUsed(true);// set grouping
anotherDFormat.setGroupingSize(3);//and size of grouping
double myDouble = 123456.78;
String numberWithSeparators = anotherDFormat.format(myDouble);//convert it
I think you have to take a look at this one
http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

DecimalFormat("#0.000") doesn't format the right way like 1.321 instead of this it delievers 1,321

I want to get a Double with 3 decimalplaces. I do this:
String sAveragePrice;
Double dAveragePrice = holePrice/(allPrices.size()); // delivers 1.3210004
DecimalFormat threeZeroes = new DecimalFormat("#0.000");
sAveragePrice = threeZeroes.format(dAveragePrice); // delivers then 1,321
After formatting I dont get a 1.321 but 1,321. And the 1,321 throws a NumberformatException later. This is when it is thrown:
Double priceInt = Double.parseDouble(sAveragePrice); // throws NumberFormatException
The strange thing is, I have this code till 3 weeks and it didn't make any problem. But today when I have started my app again it gets problem with it. But I didn't have changed anything.
Can anybody help me? I also tried this:
NumberFormat format = NumberFormat.getNumberInstance();
format.setMinimumFractionDigits(3);
format.setMaximumFractionDigits(3);
sAveragePrice = format.format(dAveragePrice);
But it also delivers me a "," instead of a "." for double.
Try using a locale for you number format.
Number format = NumberFormat.getNumberInstance(Locale.ITALIAN);
Java SDK has a limited number of predefined locale settings, so for other locales (e.g., for Russian), you can use the following snippet:
Number format = NumberFormat.getNumberInstance(new Locale("ru", "RU"));
Number format = NumberFormat.getNumberInstance(new Locale("it", "IT")); // etc...
this sample code may help you...
Locale locale = Locale.getDefault();
// set Locale.US as default
Locale.setDefault(Locale.US);
DecimalFormat decimalFormat = new DecimalFormat("##.000");
double d = 14.5589634d;
String format = decimalFormat.format(d);
System.out.println(format);// prints 14.559
// back to default locale
Locale.setDefault(locale);
Have a look at this SO question
How to change the decimal separator of DecimalFormat from comma to dot/point?
Basically your output will be Locale specific, so if you have a Locale of Frame then it will be different to a Locale of the US.
try
NumberFormat format = NumberFormat.getNumberInstance(Locale.US);
Use this type of formatting
use # instead of 0. It is the correct format to declare your pattern
String sAveragePrice;
Double dAveragePrice = holePrice/(allPrices.size());
DecimalFormat threeZeroes = new DecimalFormat("#.###");
sAveragePrice = threeZeroes.format(dAveragePrice);
Hope it will help you

How to Avoid Scientific Notation in Double?

Here is my simple code
#Override
public void onClick(View v) {
try {
double price = Double.parseDouble(ePrice.getText().toString());
double percent = Double.parseDouble(ePercent.getText().toString());
double priceValue = price * percent/100.0f;
double percentValue = price - priceValue;
moneyToGet.setText(String.valueOf(priceValue));
moneyToPay.setText(String.valueOf(percentValue));
moneyToGet.setText("" + priceValue);
moneyToPay.setText("" + percentValue);
// catch
} catch (NumberFormatException ex) {
// write a message to users
moneyToGet.setText("");
}
}
});
This is a simple code for Percentage Calculator.
What I want is to avoid the Scientific Notation in my Calculator cause I don't want to explain to user what is Scientific Notation.
For example if I want to calculate 100,000,000 and cut 50% of it, it Should give me 50,000,000 which is giving me 5.0E7 And in my case this doesn't make any sense to the user. And of course I know both results are correct.
Thanks in Advance.
Check answer here. You can write
moneyToGet.setText(String.format("%.0f", priceValue));
You can try this DecimalFormat
DecimalFormat decimalFormatter = new DecimalFormat("############");
number.setText(decimalFormatter.format(Double.parseDouble(result)));
I would suggest using BigDecimals instead of doubles. That way you will have a more precise control over your calculation precision. Also you can get a non-scientific String using BigDecimal.toPlainString().
DecimalFormat decimalFormatter = new DecimalFormat("##.############");
decimalFormatter.setMinimumFractionDigits(2);
decimalFormatter.setMaximumFractionDigits(15);
This option will help you ##.## suffix 0 before decimal, otherwise output will be .000
btc.setText(decimalFormatter.format(btcval));
use this for displaying content
Use NumberFormater like
NumberFormat myformatter = new DecimalFormat("########");
String result = myformatter.format(yourValue);

How to format a Double value properly with decimal separator?

I have an application that uses thousands separator (,) and decimal separator (.), I used this app on 2 tablets with the same languages (EspaƱol) on their configuration and when I do some process with numbers like 15,000.00 on the first one the answer was correct but in the second tablet the number changes to 15,00. I changed the language of the second to English, and it works, but how can i set this number format on code?
Sorry about the errors this is not my native language.
Thanks for the help
You could format a double value in code like this:
/**
* format a number properly
* #param number
* #return
*/
public String formatDecimal(double number) {
DecimalFormat nf = new DecimalFormat("###.###.###.##0,00");
// or this way: nf = new DecimalFormat("###,###,###,##0.00");
String formatted = nf.format(number);
return formatted;
}
And then set it to a TextView:
mytextview.setText("MyDouble: " + formatDecimal(somedouble));
You could format using
NumberFormat nf = NumberFormat.getInstance(new Locale("es", "MX")); //for example
But beware because depending on the locale, even if is the same language but different country the decimal char and grouping char my change, for example
NumberFormat nf = NumberFormat.getInstance(new Locale("es", "CO")); //displays 15.000,00
You can get an instance for a specific locale as specified by the android docs:
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
However, you should not change the locale when displaying stuff to the user imho.

Categories

Resources