How I go 12.443 to 12.40

I do the calculation and I get 12 443. I want to round it to 12.40. So I'm trying to do this, but I get 12 instead of 12.40

float result = Math.round( (new Float(result1)*0.3) + (new Float(result2)*0.7) ); vprosvasis.setText( Float.toString(result) ); 

Examples:

  • if I get 12 70,000 I want to round to 12.7
  • if I get 13.4402 to round it to 13.4.
  • 11.19 - 11.2

So, the final number will always be in the format ##. @

+4
source share
5 answers
 (float)Math.round(value * 10) / 10 

should give you the result you want.

+16
source

I have this function:

 public static float get_ROUND(float p_VALUE, int p_DECIMAL) { if (p_DECIMAL == 0) return (float) Math.round(p_VALUE); long l_LNG = 1; for (int i = 1; i <= p_DECIMAL; i++) { l_LNG = l_LNG * 10; } return (float) Math.round(p_VALUE * l_LNG) / l_LNG; } 
+2
source

Use DecimalFormat , but specify the correct rounding mode. By default, ROUND_HALF_EVEN used, but ROUND_HALF_UP is common to many financial applications.

If you really want to find and use a rounded value in further calculations (which is unusual because it gives inaccurate results), you can use BigDecimal .

I assume that result1 and result2 are instances of String .

 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 of using BigDecimal in contrast to multiplication, rounding and division, is that you can choose the rounding mode (half-up, half-even, etc.). A BigDecimal is much more expensive to manipulate than a primitive float , so that would be the best option for interactive financial applications than scientific modeling.

You can then use the rounded value as is, or convert it to a float . You can convert to String using the toString() method, but this is best done with a language-sensitive DecimalFormat object that will accept BigDecimal using the format() method.

0
source
  vprosvasis.setText(""+new DecimalFormat("#,###,###.#").format((result1*0.3)+(result2*0.7))) 
0
source
 DecimalFormat twoDForm = new DecimalFormat("#.##"); yourvalue= Double.valueOf(twoDForm.format(yourvalue)); 
0
source

Source: https://habr.com/ru/post/1347930/


All Articles