Could someone tell me how I can round a double & then remove the numbers after the decimal places - & then convert this number to a String please?
e.g. start with a double value 55.6666666666667 - round it up to a double value of 56.0000000000 -
or start with 55.333333333333 - round down to a double value of 55.0000000000 -
& then remove the decimal point and trailing zeros - convert to String.
Thanks.
The best way to round a value to the nearest integer is:
int x = (int)Math.round(55.6666666666667);
x will be 56. You can also use Math.ceil() and Math.floor() to round up or down respectively. Finally to make x a string use String.valueOf(). Like this:
String xString = String.valueOf(x);
If you wanted to do it all on one line:
String xString = String.valueOf(Math.round(55.6666666666667));
You can read more about the Math class here and the String class here.
Use the Math.round() function. You can cast it to an int to eliminate the decimal places, or you can use Math.floor() or Math.ceil() to round it down or up before casting.
Assuming that you don't actually want to save the rounded value, but just want to see it as a string, this should do everything you want, where x is the double:
String s = String.format("%.0f", x);
Related
I have Float like this one:
Float f = Float.valueOf("9.222333999444555666");
System.out.println(f); //prints 9.222334
Is there a way to count the number of digits after the . sign without using regex: f.toString().split("\\.")[1].length()?
Simply convert the value to String and get the place of the decimal point.
String s = "" + f;
int i = s.indexOf(".")
System.out.println("The number of digits after the decimal point are " + s.length()-i-1
EDIT: Read OP's comment and doubt about how to round off a float. That question is answered here: Format Float to n decimal places
For quick reference, use this: String.format("%.2f", f). What you have to understand that Java's Float and Double do not have methods and attributes for manipulating precision after the decimal point. There are several reasons for Java to do this, but all you should remember is to convert Float and Double to String, manipulate them however you want and then convert back.
This seems BEYOND easy but I cant see to find a clear answer...
Say I have a string (volume) that has a percentage...(80, 50, etc), I want to get the number in DECIMAL format, and then use that to figure out the volume to set the phone at. I already get the maxVolume...so it's just getting the correct value that's killing me...
Integer theVolume=Integer.parseInt(volume);
double decimalNumber = theVolume/100;
int calc=(int) (maxVolume*decimalNumber);
mgr.setStreamVolume(AudioManager.STREAM_MUSIC,calc, 0);
The decimalNumber is only coming out as 0.0...no matter what number I give it...?
Try doing it like this:
double decimalNumber = theVolume / 100.0;
The .0 at the end converts it to a decimal number.
edit: And for reference, it behaves like this because Java is trying to divide two integers (when using 100) so it tries to output the result as an integer. The result is a fraction so Java rounds it down by default to the closest integer to that fraction (0 in this case) and then assigns that integer value to your double. By instead using 100.0, you are telling Java to divide the integer by a double, which is then knows it can keep the fraction result and not round down.
Parse the volume as a double
double theVolume=Double.parseDouble(volume);
double decimalNumber = theVolume/100;
int calc=(int) (maxVolume*decimalNumber);
mgr.setStreamVolume(AudioManager.STREAM_MUSIC,calc, 0);
I have a problem with my division on android:
double test= 100/ 1280;
double test2 = 0.2354;
System.out.println(test);
System.out.println(test2);
I have
0.0
0.2354
I'd like to have
0.078125
0.2345
Thanks
Try this
double test= (double) 100/ 1280;
if you specify one of the numbers in your division with a decimal, i.e.
double test = 100.0/1280;
It will give you the desired output.
The reason you are not getting the correct result, is that when dividing two ints, the resulting type will also be an int. In order to avoid this, you have to typecast one of the operands in the division to a double, or - as a shorter solution when you are explicitly setting the number in the operation and not using variables - you can add the ".0" to one of the numbers.
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]);
In Java, I want to convert a double to an integer, I know if you do this:
double x = 1.5;
int y = (int)x;
you get y=1. If you do this:
int y = (int)Math.round(x);
You'll likely get 2. However, I am wondering: since double representations of integers sometimes look like 1.9999999998 or something, is there a possibility that casting a double created via Math.round() will still result in a truncated down number, rather than the rounded number we are looking for (i.e.: 1 instead of 2 in the code as represented) ?
(and yes, I do mean it as such: Is there any value for x, where y will show a result that is a truncated rather than a rounded representation of x?)
If so: Is there a better way to make a double into a rounded int without running the risk of truncation?
Figured something: Math.round(x) returns a long, not a double. Hence: it is impossible for Math.round() to return a number looking like 3.9999998. Therefore, int(Math.round()) will never need to truncate anything and will always work.
is there a possibility that casting a double created via Math.round() will still result in a truncated down number
No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.
Here are the docs from Math.round(double):
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)
For the datatype Double to int, you can use the following:
Double double = 5.00;
int integer = double.intValue();
Double perValue = 96.57;
int roundVal= (int) Math.round(perValue);
Solved my purpose.