How to get Integer of BigDecimal without separator - java

I got the following BigDecimal from a Money-Object: BigDecimal 49.99 and I need this as Integer 4999, so everything I ask for is getting rid of the separator.
I could get this BigDecimal as String and remove the separator and parse it to an Integer, but I do not think that this is pretty.
BigDecimal bigPrice = moneyPrice.getValue();
Integer price = bigPrice.intValue();
Using this only responses with 49.

You need the method:
movePointRight(int n)
javadoc link: http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#movePointRight(int)
example:
BigDecimal bd = new BigDecimal("398.0275");
System.out.println(bd.movePointRight(bd.scale()));
outputs:
3980275
If you want to use the number, just bd=bd.movePointRight(bd.scale());

Try this code:
BigDecimal db = new BigDecimal("49.99");
// multiply with 10^scale ( in your case 2)
db = db.multiply(new BigDecimal(10).pow( db.scale()));
System.out.println(db.intValue());

If it's currency and always to 2 dp, you could multiple it by 100. However as Davio comments, your code should make it clear why you're doing it.
If you want to convert, for example a price in GB pounds sterling to GB pence (100 pence in a pound) then multiplying it by 100 is the right thing to do.

It's not necessary to do any math on the BigDecimal; you can just call myBigDecimal.unscaledValue() to get the underlying unscaled BigInteger directly.

Related

How to always keep 2 decimal places in Java

I want to round off any double to a String with 2 decimal places in Java.
I have tried using DecimalFormat but it doesn't give the expected results.
Any help would be appreciated.
Ex: I/P: 3402100.5323
I want to convert this to:
O/P: 34.02
I've tried using DecimalFormat("##,##,##0.00", new DecimalFormatSymbols(Locale.US))
but this results in 34,02,100.53 whereas I want it to output 34.02
PS: If the I/P is 34.02 I would expect it to remain same even after applying the formatting
In my opinion, this can be achieved in 2 steps:
Transform the number into your customised
round-off. (3402100.5323 to 34.021005323). Divide the input with power of 10 to make it round to 2 digits.
Then transformed number can be pretty-printed to truncate value after 2 decimals (34.021005323 to 34.02)
public static void main(String[] args) {
double input = 3402100.5323;
double output = input / getDivisor(input);
System.out.printf("%.2f%n", output);
}
private static double getDivisor(double input) {
int length = String.valueOf((long) input).length();
return Math.pow(10, length - 2) ;
}
Output: 34.02
String.format("%0.2f", 34.021005323)
See
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...) and
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax
Turning one number into something completely different is, naturally, not the job of decimalformat.
To get from a number representing 3402100.5323 to the string "34.02", first you'd have to get a number that is closer to "34.02". In other words, divide by 10000.0 first.
From there, String.format("%.2f") seems like an easy path: That renders any double to a string, but never using more than 2 digits after the decimal separator. If you want 3400000.123 to turn into "34.00" and not "34", you can make that String.format("%.02f") to force the zeroes.
public String renderWhateverThatIs(double in) {
return String.format("%.02f", in / 100000.0);
}
renderWhateverThatIs(3402100.5323);
> 34,02
Note that the machine locale will dictate if you see a dot or a comma as separator. You can force the issue by explicitly passing a locale to format.
I think what you're looking for is the java.math.BigDecimal class (https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html).
In your case, it would look like this:
BigDecimal rounded = BigDecimal.valueOf(yourDoubleValueHere).setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(rounded); // 34.02
It can replace doubles (with more complex syntax though) by basically storing numbers in their decimal form, which means you could make operations on it and keep having two decimal places and avoid rounding issues.
EDIT: after thinking about it, it's probably overkill since you only want to get a String with the rounded value, but I'll leave it there just in case.
I don’t believe you can achieve what you want (First 4 digits converted into a 2 digit double with 2 decimal places) in a single step. I’ll break down the steps for an approach that I would try:
Convert the input double to a string
double d = 3402100.5323;
String dStr1 = String.valueOf(d); // dStr1 will be “3402100.5323”
Next, remove the decimal from the string
String dStr2 = dStr1.replace(‘.’,’’); // dStr2 will be “34021005323”
Then, grab the first 4 digits you are interested in
String dStr3 = dStr2.substring(0,4); // dStr3 will be “3402”
Finally, insert a decimal point
String result = dStr3.substring(0,2) + “.” + dStr3.substring(2); // result will be “34.02”
You can use format for this try this out it work 100% for me.
String.format("%.2f", value)
Helpful link
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

How to format a number in Java and also keep the decimals?

I'm trying to show milliseconds as seconds while also keeping the decimals e.g. I have 1234 milliseconds and I want to show this as 1.234 seconds.
Decimal duration = 1234;
NumberFormat formatter = new DecimalFormat("#0.000");
String durationStr = formatter.format(duration / 1000);
Any suggestions how I could do this?
It sounds like you should be using BigDecimal - create a BigDecimal from the long, and then scale it by 3 places:
BigDecimal bd = new BigDecimal(duration).scaleByPowerOfTen(-3);
String durationStr = formatter.format(bd);
By using BigDecimal instead of double, you know that you'll still have exactly the value you're really considering, rather than simply "the nearest approximation that double can hold".
You may well also want:
formatter.setMinimumFractionDigits(3);
formatter.setMaximumFractionDigits(3);
... to ensure that you always get exactly 5 digits. (Assuming you want 1 second to be "1.000" for example.)
Use a double to divide the number 1000d.
String durationStr = formatter.format(duration / 1000d);

Equivalent to bcdiv from php in java

What is the equivalent of bcdiv(string, string [, int]) in java
the function divides two arbitrary precision numbers
I would like for instance to use:
bcdiv(10000,100, 2) results in 100.00
or
bcdiv(10000,100, 3) result in 100.000
I am more interested in the precision it gives.
I would like its equivalent in java
link to the php manual
The BigDecimal class allows arbritary precision math. In particular see the divide method.
BigDecimal a = new BigDecimal(10000);//Can take int
BigDecimal b = new BigDecimal("100");//Or string
BigDecimal answer = a.divide(b);
The number has defined structure, but you can format String produced from this number:
String.format("%.2f",10000/100f);

How to round an answer to a mathematical equation

All-
I have an app in which the users inputs data such as the cost of a dinner bill and the tip percentage and the number of people. The app than takes the numbers and outputs the total bill cost and the amount each person has to pay. I am almost there but when the user inputs numbers that don't work well I get outputs like $23.576 or $34.999999999. My question is how do I make the app round the two output answers to two decimal places ($55.349 goes to $55.35)?
Thanks in advance!
String roundTwoDecimals(double d) {
DecimalFormat formatter = new DecimalFormat("#.##");
return formatter.format(d);
}
You can use Math.round like so:
double data = 55.349; // Your data value of whatever
int decimalPlaces = 2;
double roundBase = Math.pow(10, decimalPlaces);
data = (double)(Math.round(data * roundBase)) / roundBase;
System.out.println(data); // Prints "55.35"
Keep in mind, however: you should NOT use double when it comes to financial applications. Since yours appears to be small-scale, you should be fine, however, BigDecimal is much easier to use for purposes like these.
How to use BigDecimal: clicky.

Print the number of digits before a decimal point

I know there are ways to get the number of digits after a decimal point, for instance the substring method, but how would I go about doing this for the number of digits before a decimal place?
I need to use this to convert US change (double) into Euro change(double). The way I would like to do this is by taking the number before a decimal (such as $1.) and times it by its euro equivalent (.7498) and take the number after a decimal (.16) and times that by its .01 euro coin value (.0075), add both values together to get the euro equivalent of $1.16 (.8698).
To get the number before decimal point,do this:
String str = new Double(your_double_number).toString().subString(0,str.indexOf('.'));
double v = Double.valueOf(str);
If you are using '$' sign then take 1 in place of 0.
Hope it will help you.
convert US change (double) into Euro change(double)
Please don't do that. Never, never, ever use double or float to represent money, because those datatypes cannot represent most decimal fractions, so you get rounding errors before you even start to do any calculations.
Instead, use BigDecimal.
First of all - just multiplying the Dollar value by the exchange rate will get you the euro value so there's no need to do that as far as i can see - you will just introduce rounding errors.
But if you did need to - just use substring
String dollarVal = "$1.16"
String justFullDollar = dollarVal.substring(1, dollarVal.indexOf("."));
String justCents = dollarVal.substring(dollarVal.indexOf(".")+1);
The Correct way would be to store all you money as integers or arbitrary precision objects that way you get no floating point errors too.
Convert to cents, multiply and convert back again.
e.g.
String dollarVal = "$1.16"
BigDecimal dollars = new BigDecimal(dollarVal.substring(1)); //1.16
BigDecimal cents = dollars.multiply(new BigDecimal(100)); //116
BigDecimal eurocents = cents.multiply(new BigDecimal(exchangeRate)); //86.9768
BigDecimal euros = eurocents.divide(new BigDecimal(100)); //0.869768
DecimalFormat formatter = new DecimalFormat("###.00");
String euroVal = "€" + formatter.format(euros);
You can use
String s[] = new Double(your number).toString().split(".");
The s[0] is the number before decimal point. and s[1] is the number after decimal point.
Both are in String, so you need to parse them into double using
double num1 = Double.parseDouble(s[0]);
double num2 = Double.parseDouble(s[1]);

Categories

Resources