This question already has answers here:
percentage of two int?
(4 answers)
Closed 5 years ago.
I have such code:
int number1 = 20;
int number2 = number1/100;
I want to get percentage of number1 as 0,2 -> I suppose int should be converted into some other type. But I need 0,2 to use for BigDecimal number. How can I get this 0,2 from int number1 = 20?
int number1 = 20 has to be in that type.
Will be grateful for help.
Using a BigDecimal is appropriate here. You can use BigDecimal.valueOf in order to convert int to BigDecimal. Then, you can divide by specifying a scale and a rounding mode.
Example :
System.out.println(
BigDecimal.valueOf(20).divide(BigDecimal.valueOf(100), 1, RoundingMode.HALF_UP)
);
Will display :
0.2
With a different scale :
System.out.println(
BigDecimal.valueOf(20).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP)
);
It will display :
0.20
Or like stated in the question comments, you can also create directly the BigDecimal from a String :
System.out.println(new BigDecimal("0.2"));
Divide the int by a floatvalue to give to it a floating number representation and assign it to a floating number.
float number2 = number1/100F;
Related
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 5 years ago.
I have the number "159.82" and I need to get it to print just "82"
What I have been trying is something along the lines of
double total = 159.82;
System.out.println(total - (int) total);
But that leaves me with 0.8199999999999 so clearly I am doing something wrong.
Simple way: Turn it into an String, use indexOf to find the ".", use substring to print 82.
Would this fit what you're looking for? It outputs the decimal value, rounded to two places, as a String.
double total = 159.82;
String decimalValue = String.format("%.2f", total).split("\\.")[1];
System.out.println(decimalValue);
(Prints "82")
Due to how float/double works, the easiest solution could be to work with strings. This will return the decimals of any double input.
double input = 159.82;
String decimals = Double.toString(input);
decimals = decimals.substring(decimals.lastIndexOf('.') + 1);
System.out.println(decimals);
// prints "82"
final int fraction = Integer.valueOf((total+"").replaceFirst("-?\\d+\\.", ""));
System.out.println( fraction );
Another solution with replaceAll, so you can replace everything until the dot :
double total = 159.82;
System.out.println(String.valueOf(total).replaceAll("^.*\\.", ""));// output = 82
This can work either with negative numbers for example :
double total = -159.82; // output = 82
Another solution if you want to get only 2 numbers then you can use :
double total = 159.82; // positive or negative
int result = Math.abs((int) (total * 100) % 100);
System.out.println(result); // output = 82
This question already has answers here:
Always Round UP a Double
(8 answers)
Closed 7 years ago.
Is there a way to automatically round up a value in java?
For example:
//generate a random integer value
int randomVal = RandomHelper.nextIntFromTo(1, otherVal);
/* then divide the integer value in half... the error I am getting is that its a double, probably
because the number generated isn't an even number, but I NEED it to be an integer. Can I round up?*/
int value = randomVal * 0.5;
You can add 1 then divide by 2 instead of multiplying by 0.5. That way, you avoid a floating point operation followed by a conversion to int.
int value = (randomVal + 1) / 2;
Use Math.ceil():
int value = (int)Math.ceil(randomVal * 0.5);
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
Is there any way to calculate (for example) 50% of 120?
I tried:
int k = (int)(120 / 100)*50;
But it doesn't work.
int k = (int)(120 / 100)*50;
The above does not work because you are performing an
integer division expression (120 / 100) which result is
integer 1, and then multiplying that result to 50, giving
the final result of 50.
If you want to calculate 50% of 120, use:
int k = (int)(120*(50.0f/100.0f));
more generally:
int k = (int)(value*(percentage/100.0f));
int k = (int)(120*50.0/100.0);
Never use floating point primitive types if you want exact numbers and consistent results, instead use BigDecimal.
The problem with your code is that result of (120/100) is 1, since 120/100=1.2 in reality, but as per java, int/int is always an int.
To solve your question for now, cast either value to a float or double and cast result back to int.
I suggest using BigDecimal, rather than float or double. Division by 100 is always exact in BigDecimal, but can cause rounding error in float or double.
That means that, for example, using BigDecimal 50% of x plus 30% of x plus 20% of x will always sum to exactly x.
it is simple as 2 * 2 = 4 :)
int k = (int)(50 * 120) / 100;
Division must be float, not int
(120f * 50 / 100f)
You don't need floating point in this case you can write
int i = 120 * 50 / 100;
or
int i = 120 / 2;
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 9 years ago.
I have the following and the question is, for example if zzi = 95 then myNum will be correctly displayed as 32.33, exactly as I want it too with two decimal places.
However if zzi = 94, myNum will be displayed as 32.0 instead of 32.00
How to display it as 32.00?
float xFunction(int zzi) {
float myNum = (zzi + 2);
myNum = myNum / 3;
int precision = 100; // keep 4 digits
myNum = (float) (Math.floor(myNum * precision + .5) / precision);
return myNum;
}
Thanks before.
Your question is not so much about rounding a number as it is about rounding a display or String representation of a number. The solution:
Use new DecimalFormat("0.00");
Or String.format("%.2f", myNumber);
Or new java.util.Formatter("%.2f", myNumber);
Or System.out.printf("%.2f", myNumber);
Note: avoid use of float whenever possible, and instead prefer use of double which greatly improves numeric precision at little cost. For financial calculations use neither but instead opt for integer calculations or use BigDecimal.
Remember:
1) printing the number displaying two decimal places is very different from rounding the actual value. In other words "representation" != actual value.
2) floating point values are always imprecise. Even with rounding, you may or may not get an "exact value".
Having said that, the simplest approach is:
float myNum = ((123.456 * 100.0) + .5) / 100.0;
new DecimalFormat("#.##").format(myNum );
You can use DecimalFormat
System.out.println(new DecimalFormat("0.00").format(xFunction(94)));
You should work on the printing function. I assume you are using a System.out.println: replace it with
System.out.format("%.2f", numberToPrint);
Read the docs for that function to discover more about format strings.
This question already has answers here:
Are there any functions for truncating a double in java?
(11 answers)
Closed 9 years ago.
I want to truncate the double.
e.g.
double d=3.123456789087654;
if I want to truncate It to the 10th digit after the decimal
the result should be
result: 3.1234567890
I don't need round off value as a result
I tried my own function as
static double truncateDouble(double number, int numDigits) {
double result = number;
String arg = "" + number;
int idx = arg.indexOf('.');
if (idx!=-1) {
if (arg.length() > idx+numDigits) {
arg = arg.substring(0,idx+numDigits+1);
result = Double.parseDouble(arg);
}
}
return result ;
}
but didn't get the appropriate result as I want..
can anybody please help me to clear my problem.
Does java supports such any function that supports truncation not round off??
In general, you can't, at least not by using double. The reason is that many numbers simply can't be represented exactly, even if they have a small number of decimal digits.
Take 0.1 as an example. The nearest double is 0.1000000000000000055511151... and no amount of truncation would give you exactly 0.1.
You can use the DecimalFormat class.
double d = 3.123456789087654;
DecimalFormat newFormat = new DecimalFormat("#.##########");
double tenDecimal = Double.valueOf(newFormat.format(d));
this will round the last digit.
I am agree with NPE. no amount of truncation would give you exactly 0.1.
only way is to convert in to string and after substring convert back to double.