Use a DecimalFormat
, but specify the correct rounding mode. By default it uses ROUND_HALF_EVEN
, but ROUND_HALF_UP
is common for a lot of financial applications.
If you really want to find and use the rounded value in further calculations (which is unusual because it produces inaccurate results), you can use BigDecimal
.
I assume result1
and result2
are String
instances.
float value = Float.parseFloat(result1)*0.3F + Float.parseFloat(result2)*0.7F;
BigDecimal d = new BigDecimal(String.valueOf(value));
BigDecimal rounded = d.setScale(1, BigDecimal.ROUND_HALF_EVEN);
The main advantage to using BigDecimal
as opposed to multiplying, rounding, and dividing, is that you can select the rounding mode (half-up, half-even, etc.). A BigDecimal
is a lot more expensive to manipulate than a primitive float
, so this would be a better option for an interactive financial application than a scientific simulation.
You can then use the rounded
value as is, or convert it to a float
. You can convert to a String
with the toString()
method, but this is better done with a locale-sensitive DecimalFormat
object, which will accept BigDecimal
with its format()
method.