开发者

How do I round 12.443 to 12.40

I'm making a开发者_JAVA百科 calculation and I'm getting 12,443. I want to round it to 12,40. This is the way I'm trying to do it but I'm getting 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,70001 I want to round to 12,7
  • if i get 13,4402 to round it to 13,4
  • 11,19 to 11,2

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


(float)Math.round(value * 10) / 10

should give you the result you want.


i have this function to do it :

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;
}


DecimalFormat  twoDForm = new DecimalFormat("#.##");
yourvalue=  Double.valueOf(twoDForm.format(yourvalue));


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.


    vprosvasis.setText(""+new DecimalFormat("#,###,###.#").format((result1*0.3)+(result2*0.7)))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜