java - Android round float

I would like to round a float to two digits and then set it as the text of a button. I have tried multiple techniques and none of them seem to work. Can you tell me what i am doing wrong or a new way to do this. what i have tried

DecimalFormat price = new DecimalFormat("#.00");
                //  price.format(cheeses);
public static String roundToOneDigit(float paramFloat) {
    return String.format("%.2f%n", paramFloat);
button3.setText("Increase price" + "$%3.2f\n"+ cheeses);
                    //float f = round(cheeses,2);
                //  float f = new DecimalFormat("#.##").format(cheeses).tofloat();
f *= 100;
                //  f = (float)Math.round(f)/100; 

2 Answers

  1. Leopold- Reply

    2019-11-14

    Try this:

    public static String roundToOneDigit(float paramFloat) {
        return String.format("%.2f%n", paramFloat);
    }
    
    ...
    button3.setText("Increase price " + roundToOneDigit(cheeses) + "\n");
    

    The rest is unnecessary.

  2. Loren- Reply

    2019-11-14

    Your code snippet has a lot of errors. For one, syntax is wrong, the method does not have closing bracket. Also, in your button3.setText, in your question , you said you want to round a float and then set to the button3 but in your code snippet, you did not called the method roundToOneDigit? Anyway, look below, try this into your android code.

    import java.text.DecimalFormat;
    
    
    public class AndroidClass
    {
    
        public static String roundToOneDigit(float paramFloat)
        {
            DecimalFormat price = new DecimalFormat("#.00");
            return price.format(paramFloat);
        }
    
        public static void main(String[] args)
        {
            float cheese = 3;
            System.out.println("Increase price " + roundToOneDigit(cheese));
        }
    
    }
    

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>