When I do the 162/11 calculation, the result is 14,72727272727273
. But when I use the code System.out.printf("%.1f", teste);
, the number 14,8
is displayed.
I would like a way to save only 8 in a int
.
When I do the 162/11 calculation, the result is 14,72727272727273
. But when I use the code System.out.printf("%.1f", teste);
, the number 14,8
is displayed.
I would like a way to save only 8 in a int
.
Why not do this?
double teste = 162.0 / 11.0;
System.out.printf("%d", ((int) Math.ceil(teste * 10)) % 10);
The idea here is:
Multiply by 10 so that the first digit after the comma becomes the last digit before it.
Math.ceil
round the number up. So your 7 digit becomes an 8.
cast for int
cuts all digits after the one that interests you.
The rest of the division by 10 cuts all digits ahead of the one that interests you.
As a result, you will get an integer from 0 to 9 that corresponds to the digit you want and nothing else.
In addition, there is a very interesting advantage: This is all solved only with math without you having to use String
s at any time.
If you want to round down instead of up, just replace ceil
with floor
". If it is desired to round to the nearest integer, then > rint
.
For the value that follows the comma, just take the part after the comma (works with positives and negatives):
double valor_decimal = valor - (int)(valor);
Or, if you prefer rounding, do:
String valorString String.format("%.1f", valor);
double valorArredondado = Double.parseDouble(valorString);
Then if you just want to get a number after the comma do:
int valor final = (int)valor_decimal * 10;
If you want to format for all numbers after the comma, you can try to convert to string, and multiply the size returned by the function split
:
String[] divisor = valor_decimal.toString().split("\,");
int valor final = (int)valor_decimal * divisor[1].length();
The problem with this second solution is that it can representation of an integer, to get around this you can use a BigInteger to ensure it does not happen!
References: