Print the number of digits before a decimal point - java

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]);

Related

how do i restric a float value to only one placess after decimal in kotlin android

I have a number with some number decimal places,
How can i round this float number with one number decimal places
for example
1.366565646 convert to 1.3
In your case I think you need to trim the number not round it,
You can use this:
double d = 1.366565646;
DecimalFormat df = new DecimalFormat("#.#");
double p = Double.parseDouble(df.format(d));

Keep up to 3 decimals without doing any rounding

I have a double that I want to keep only 3 decimal places but without applying any rounding at all.
E.g. 92.36699 should be 92.366
I tried the following:
DecimalFormat nf= new DecimalFormat("#0.000");
String number = nf.format(originalNumber);
But this results in 92.367
How can I do what I need?
This isn't "no rounding", it's DOWN rounding. Simply set the roundingMode.
DecimalFormat nf = new DecimalFormat("#0.000");
nf.setRoundingMode(RoundingMode.DOWN);
String number = nf.format(originalNumber);
Note the difference between FLOOR and DOWN - only relevant for negative numbers. FLOOR rounds towards negative infinity therefore -92.36699 would become "-92.367".

Split number into an integer and decimal

Input 23.893 would become INTEGER - 23, DECIMAL - 0.893
Here's the key snippet from my code
double realNumber = scan.nextDouble(); \\store the keyboard input in variable realNumber
double integerPart = Math.floor(realNumber); \\round down eg. 23.893 --> 23
double fractionPart = realNumber - integerPart; \\find the remaining decimal
When I try this with long numbers the decimal part differs slightly from the actual.
Input - 234.324112341234134 becomes INTEGER - 234.0,
DECIMAL - 0.3241123412341267
As stated by #dasblinkenlight you can use methods from BigDecimal and combine them with a splitter. I wouldn't count the decimal points though, easier to stick with BigDecimal.
For example:
public static void main(String[] args) {
String realNumber = "234.324823783782";
String[] mySplit = realNumber.split("\\.");
BigDecimal decimal = new BigDecimal(mySplit[0]);
BigDecimal real = new BigDecimal(realNumber);
BigDecimal fraction = real.subtract(decimal);
System.out.println(String.format("Decimal : %s\nFraction: %s", decimal.toString(),fraction.toString()));
}
This outputs the following:
Decimal : 234
Fraction: 0.324823783782
Your program's logic is correct. The problem is the representation that you have selected for your input.
double is inherently imprecise, so the lower-order digits are often not represented correctly. To fix this problem, you could use BigDecimal or even a String data type.
If you use BigDecimal, simply rewrite your algorithm using the methods of BigDecimal. If you use String, split user input at the decimal point, and add required zeros and decimal points after the whole part and before the fractional part.

How to return a double with two decimal places?

I want to return a double with 2 decimal places (i.e. 123.00). The following are part of the codes. The output is always 123.0. How to get a two decimal places?
public static double getPrice(){
double price = Double.valueOf(showInputDialog("Stock's price : "));
DecimalFormat rounded = new DecimalFormat("###.00");
double newPrice = Double.valueOf(rounded.format(price));
System.out.println(newPrice);
return newPrice;
}
As long as the return type of your function is double, the short answer is "you can't".
Many numbers that have no more than two decimal digits cannot be represented exactly as double. One common example is 0.1. The double that's nearest to it is 0.100000000000000005551115...
No matter how much rounding you do, you wouldn't be able to get exactly 0.1.
As far as your options go, you could:
accept the rounding issues associated with using double;
return an int (i.e. the rounded value multiplied by 100);
return a String;
return a BigDecimal.
In particular, if you're representing monetary amounts, using double is almost certainly a bad idea.
When formatting, you're making a string from a double. Don't convert your formatted string to a double again :
String formattedPrice = rounded.format(price);
System.out.println(formattedPrice); // prints 123.00 or 123,00, depending on your locale
A double keeps a numerical value following IEEE754, it doesn't keep any formatting information and it's only as precise as the IEEE754 double precision allows. If you need to keep a rendering information like the number of digits after the comma, you need something else, like BigDecimal.

java rounding to two decimals

I have a number
double num = 1.234567;
and I'm trying to keep only two decimals
num = (int)((num * 100) + 0.5) / 100.0;
but the actual number I got is 1.230000000001. How can I get rid of the 0000000001 part?
Try DecimalFormat:
DecimalFormat twoDp= new DecimalFormat("#.##");
Double.valueOf(twoDp.format(num));
You can't, unless you switch to a decimal radix. Doubles and floats don't have decimal places, they have binary places, so you can't round or truncate them to specific numbers of decimal places except in the cases where the value representations are congruent, i.e. the negative powers of 2.
So you have to either use DecimalFormat if you are presenting the result, or BigDecimal if you want to keep computing with it.
Any solution that ends by turning the value back into floating point is incorrect.
String result = String.format("%.2f", num);
Try this .. this should solve it
Double num = //value
num = //arithmetic
String temp =num.toString().split("\\.")[0];
int precision=temp.length();
BigDecimal b =new BigDecimal(num,new MathContext(precision+2));
System.out.println(b.doubleValue());

Categories

Resources