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);
Related
I have below piece of code:
I am passing value "55.00000000000000" and getting output as 55.00000000000001.
But when i passed "45.00000000000000" and "65.00000000000000" i get output as 45.0 and 65.0.
Can someone please help me to get correct output as 55.0.
NumberFormat numberFormat = NumberFormat.getPercentInstance(Locale.US);
if (numberFormat instanceof DecimalFormat) {
DecimalFormat df = (DecimalFormat) numberFormat;
df.setNegativePrefix("(");
df.setNegativeSuffix("%)");
}
Number numericValue = numberFormat.parse("55.00000000000000%");
numericValue = new Double(numericValue.doubleValue() * 100);
System.out.println(numericValue);
The problem here is that numericValue is mathematically supposed to be 0.55. However, it will be a Double (because numberFormat.parse() can only return a Long or a Double). And a Double cannot hold the value 0.55 exactly. See this link for a complete explanation of why. The result is that as you do further computations with the inexact value, roundoff errors will occur, which is why the result being printed out is not quite the exact value. (A Double also cannot be exactly 0.45 or 0.65; it just happens that when multiplying by 100, the result rounds to the correct integer.)
When dealing with decimal values such as money or percentages, it's preferable to use BigDecimal. If the NumberFormat is a DecimalFormat, you can set things up so that parse returns a BigDecimal:
if (numberFormat instanceof DecimalFormat) {
DecimalFormat df = (DecimalFormat) numberFormat;
df.setNegativePrefix("(");
df.setNegativeSuffix("%)");
df.setParseBigDecimal(true); // ADD THIS LINE
}
Now, when you use numberFormat.parse(), the Number it returns will be a BigDecimal, which is able to hold the exact value 0.55. Now you have to avoid converting it to a double, which will introduce a roundoff error. Instead, you should say something like
Number numericValue = numberFormat.parse("55.00000000000000%");
if (numericValue instanceof BigDecimal) {
BigDecimal bdNumber = (BigDecimal) numericValue;
// use BigDecimal operations to multiply by 100, then print or format
// or whatever you want to do
} else {
// you're stuck doing things the old way, you might get some
// inaccuracy
numericValue = new Double(numericValue.doubleValue() * 100);
System.out.println(numericValue);
}
use this line of code
System.out.println(String.format("%.1f", numericValue));
Where format method use to format your data.
public class Dummy {
public static void main(String args[]) {
String x = "1.234.567,89 EUR";
String e = " EUR";
List<BigDecimal> totals = new ArrayList<BigDecimal>();
totals.add( new BigDecimal(x.replaceAll(" EUR","").replaceAll("\\.","").replaceAll(",",".")));
System.out.println(totals.get(0).add(new BigDecimal(0.10).setScale(3,0)));
}
}
With current code I get 1234567.991 and setting it to setScale(2,0) I get 1234568.00 what I am looking for is 1234567.99. Any help?
Use
System.out.println(totals.get(0).add(new BigDecimal(0.10)
.setScale(2, BigDecimal.ROUND_HALF_UP)));
Out put
1234567.99
I think there must be an inbuilt Java function for this. But otherwise, you can do it with simple mathematics.
You can multiply the number with 100. And then use ceiling or floor function of Java. And then divide it with 100. You got your desired result.
Do not use
new BigDecimal(0.10)
which is both inprecise and does not give a precision/scale of 2.
But use
new BigDecimal("0.10")
This preserves the scale.
This will give desired output.
If you want to go with double at that time we can use DecimalFormat but in bigdecimal setScale is used.
BigDecimal.valueOf(1234567.991).setScale(2, BigDecimal.ROUND_HALF_UP)
.doubleValue();
OUTPUT
1234567.99
I have an assignment and I need to get an input from the user to refine an answer to an x(the input of the user) number of decimal places. I'm going to refine my answer until there aren't any changes in the x decimal place.Can you please help on how I could achieve this answer?
It's not very clear what you are trying to achieve, but I think you want to accept a number and then round it up as the user specifies it.
Java's BigDecimal http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html class has all the functions you may need for this purpose. Please don't use the primary data types (float, double) as they will result in rounding errors sooner or later.
While it is true what #Thihara answers, maybe you need a bit simpler approach. Unless you need the precision of BigDecimal, you can do this:
int x = 4;
double value = 3.141593;
long answer = (long) (value * Math.pow(10, x));
The point is: multiply the value by 10^x and then convert to long (or int). Of course, this only works for small x.
There are a bunch of issues floating around here, that you should be aware of.
The first is that if you use a floating point number to represent your answer, you cannot represent every possible real number so you almost definitely will get rounding errors. Check out http://floating-point-gui.de/ for great information about this.
Secondly, when you print a float or double value, Java does some magic with it so that it looks nice. See Float.toString(float) and Double.toString(double) for more information.
So in reality, if you enter
double answer = 3.14159265;
it is stored as
3.141592650000000208621031561051495373249053955078125
which you can see using
System.out.println(new BigDecimal(answer));
So assuming you get your answer as a double (or float), you should use BigDecimal's setScale method. Also, if you want to limit the decimal places that your user can choose to the number visible when you print the double as a string, pass String.valueOf(answer) to BigDecimal's constructor.
Here is a little program that demonstrates how to do this
public static void main(String[] args) {
double answer = 3.14159265;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String input = null;
do {
System.out.println("Answer: " + answer);
System.out.println("How many decimal places do you want? ");
try {
input = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (input != null) {
try {
int decimalPlaces = Integer.parseInt(input);
if (decimalPlaces < 0) {
System.out.println("Enter a positive value.");
} else {
BigDecimal scaled = new BigDecimal(
String.valueOf(answer));
if (decimalPlaces > scaled.scale()) {
System.out
.println("Answer does not have that many decimal places.");
} else {
scaled = scaled.setScale(decimalPlaces,
RoundingMode.HALF_EVEN);
System.out.println("Rounded answer: " + scaled);
}
}
} catch (Exception e) {
System.out.println("Not a valid number.");
}
}
} while (input != null);
}
Most of the code is error/input checking. The real work is done by setScale. Just keep in mind that there are many boundary conditions when working with floating point numbers, and you should be good!
I'm fairly new to the whole android scene, and I decided to start off with something simple, a Celsius to Fahrenheit converter. Here's the block of code I'm using to do the actual math (x-32)*5/9 where x=input for Celsius Temp.
convertbutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
double result = new Double(input.getText().toString())-32*5/9;
output.setText(Double.toString(result));
I know that x-32*5/9 is not a valid way to do the (x-32)*5/9 formula, but I can't put the -32 in parenthesis. Just looking for ways to get it to subtract 32 from the input first, and then for it to multiply that by 5/9. Any help would be much obliged.
You may have been confused by the parentheses in this expression:
new Double(input.getText().toString())-32*5/9
It would work if you parenthesized the whole thing up to 32:
(new Double(input.getText().toString())-32)*5/9
^ here and here ^
But it’s easier to read if you put the value in a temporary variable:
double input_value = new Double(input.getText().toString());
double result = (input_value - 32) * 5/9;
You are probably looking for Double.parseDouble(String);
Here is an example...
String s = "56.7";
double input = Double.parseDouble(s);
input = (input - 32d) * (5d/9d);
Edit: the d is necessary to force java to interpret the constants as doubles
I have a JTable where i enter some values. This is the listener function to know if it has been made any change at the values, so i can update them. Values must have the format indicated (#.###), so I'm doing this fix to round the float to 3 decimal places if the client enter more than 3.
private class CambioTablaPretratamientoListener implements TableModelListener{
public void tableChanged(TableModelEvent e){
try{
if(enviarDatosADispositivo){
TableModel model = (TableModel)e.getSource();
float value = Float.parseFloat((String)model.getValueAt(e.getLastRow(), 1));
DecimalFormat dec = new DecimalFormat("#.###");
String aux = dec.format(value);
if(model.getValueAt(e.getLastRow(), 1).equals(aux))
return;
else
model.setValueAt(aux, e.getLastRow(), 1);
value = Float.parseFloat(aux);
String nombreAtributo = (String)model.getValueAt(e.getLastRow(), 0);
nodoAModificar.setPretratamientUserParameter(nombreAtributo, value);
}
}catch(BusinessException ex){
ex.printStackTrace();
}
}
}
Code seems to work at first, because it rounds and the number appears in the table, but the value is not getting updated. I guess I'm doing something wrong with the DecimalFormat, because if I leave the function like this one, it works:
private class CambioTablaPretratamientoListener implements TableModelListener{
public void tableChanged(TableModelEvent e){
try{
if(enviarDatosADispositivo){
TableModel model = (TableModel)e.getSource();
float value = Float.parseFloat((String)model.getValueAt(e.getLastRow(), 1));
String nombreAtributo = (String)model.getValueAt(e.getLastRow(), 0);
nodoAModificar.setPretratamientUserParameter(nombreAtributo, value);
}
}catch(BusinessException ex){
ex.printStackTrace();
}
}
}
And finall
You seem to think that converting a floating-point number to a String and back again can cause it to have a definite number of decimal places. This is fallacious. FP values don't have any decimal places. They have binary places. These only correspond to fixed numbers of decimal places if the fractional part is a negative power of 2, e.g. 0.5, 0.125, 0.0625, etc.
Instead, apply your DecimalFormat as a custom table cell renderer.
If you use BigDecimal, you could actually truncate the numbers, instead of trying to use Float's (lack of) precision.