How do I use BigDecimal's setScale to get two digits precision - java

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

Related

Converting large scientific number to long

I've spend a long time now, trying to convert the number 1.2846202978398e+19 in java, without any luck. Currently what I'm trying to do (long)Double.parseDouble(hashes), however this gives 9223372036854775807, which is obviously incorrect. The actual number should look something like this 12855103593745000000.
Using int val = new BigDecimal(stringValue).intValue(); returns -134589568 as it's unable to hold the result. Switching the code to long val = new BigDecimal(hashes).longValue(); gives me -5600541095311551616 which is also incorrect.
I'm assuming this is happening due to the size of a double compared to a long.
Any ideas?
Did you try to use String.format :
String result = String.format("%.0f", Double.parseDouble("1.2846202978398e+19"));
System.out.println(result);
Output
12846202978398000000
Edit
Why you don't work with BigDecimal to do the arithmetic operations, for example :
String str = "1.2846202978398e+19";
BigDecimal d = new BigDecimal(str).multiply(BigDecimal.TEN);
// ^^^^^^^^------example of arithmetic operations
System.out.println(String.format("%.0f", d));
System.out.println(String.format("%.0f", Double.parseDouble(str)));
Output
128462029783980000000
12846202978398000000
Your value exceeds the maximum size of long. You can not use long in this situation.
Try
BigDecimal value = new BigDecimal("1.2846202978398e+19");
After that, you can call
value.toBigInteger()
or
value.toBigIntegerExact()
if needed.
What about:
System.out.println(new BigDecimal("1.2846202978398e+19").toBigInteger());

How to remove the E7 when a number is too high? [duplicate]

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 add a very small number and a very large number

I am pretty new to Java. I am learning numerical computation at the moment. How does one add and multiply a very small number and a very large number, say something of order $10^{-20}$ and something of order $10^{20}$ to arbitrary precision.
Take a look at the BigDecimal class. From the Javadoc:
Immutable, arbitrary-precision signed decimal numbers.
and:
The BigDecimal class gives its user complete control over rounding behavior.
For your example:
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal big = new BigDecimal("10e20");
BigDecimal small = new BigDecimal("10e-20");
BigDecimal ans = big.add(small);
System.err.println("Answer: " + ans);
}
}
Running gives the following:
$ java Main
Answer: 1000000000000000000000.00000000000000000010
Try the following (didn't count the zeros). You may find other methods to construct 10^20/10^-20 more suitable.
System.out.println( new BigDecimal("0.0000000000000000000000000000001").add( new BigDecimal
("100000000000000000000000000000000")));

Java : Rounding a decimal value to HALF_EVEN

I have been trying to write a java code to Round a value to the below requirement.
If x=63.88 => roundedValue= 64.00;
If x=63.50 => roundedValue= 64.00
If x=63.32 => roundedValue= 63.32
I tried with the different roundingModes like CEILING, DOWN, FLOOR, HALFDOWN.
I also tried Math.round();
But I'm unable to get the expected output.
My input is a string and output is a string.
Please find the code snippet I tried below
BigDecimal value1 = new BigDecimal(input);
value1=value1.setScale(2, RoundingMode.HALF_EVEN);
//float rounded=Math.round(amount);
String finalValue=String.valueOf(value1);
I'm unable to get the desired output. Please let me know how to achieve this?
ps: should i consider using float or BigDecimal??
if(x%1 >= .5)
{ x = Math.round(x) }
else //do nothing
This seems like it would give you the desired output you are looking for. So if you really wanted to you could override or create your own method to call for the rounding
What you want to do with this, is providing your own MathContext to specify the behavior of the rounding you want to perform.
The closest you will get to your current requirements is either: using RoundingMode.HALF_UP or RoundingMode.UNNECESSARY
For that you will have to use BigDecimal anyways, since Double and Float do not expose rounding.
public static void main(String args[]) {
Double d = 63.18;
DecimalFormat df = new DecimalFormat("00.00");
if(d % 1 >= 0.5)
System.out.println(df.format(Math.round(d)));
else
System.out.println(d);
}
As in your post, using BigDecimal is the way to go, if you want to use decimal rounding.
If you want to round up for numbers >= X.5 and avoid rounding for numbers < X.5 then you can use this code:
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Round {
public static void main(String[] args) {
System.out.println(round("63.88"));
System.out.println(round("63.50"));
System.out.println(round("63.32"));
}
private static BigDecimal round(String input) {
BigDecimal value = new BigDecimal(input);
BigDecimal rounded = value.setScale(0, RoundingMode.HALF_UP);
if (rounded.compareTo(value) > 0)
return rounded.setScale(2);
return value;
}
}
The output is:
64.00
64.00
63.32

Either showing maximum number of decimal places, or don't show at all

Currently, using DecimalFormat I would like to show maximum number of decimal places, or don't show at all. For instance,
100.0 shown as "100"
100.123 shown as "100.123"
100.123456789012345 shown as "100.123456789012345"
Using format as
new DecimalFormat("0.###"); is partially correct. It works for 1st case, 2nd case but not 3rd case. As, I have no idea how much # should I have?
So, may I know what is the correct DecimalFormat I should use?
You can use setMaximumFractionDigits() to do this. The maximum value is 340, so might as well set it to that value:
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat();
formatter.setMaximumFractionDigits(340);
BigDecimal[] numbers = {new BigDecimal("100.0"), new BigDecimal("100.123"), new BigDecimal("100.123456789012345")};
for (BigDecimal number : numbers) {
System.out.println(formatter.format(number));
}
}
prints
100
100.123
100.123456789012345

Categories