How to I round a number in Java? Like, I have this number 3.4666666666663 and i would like to round it to the nearest floating number, which would be 3.5. I don't want to round it to 4
            Asked
            
        
        
            Active
            
        
            Viewed 241 times
        
    0
            
            
         
    
    
        Matheus Fróes
        
- 141
- 10
- 
                    When you say "this number", what is it to begin with? A `float`? A `double`? A `BigDecimal`? – fge Oct 26 '14 at 01:18
- 
                    4I believe your definition of _nearest floating number_ is not universally accepted. – Keppil Oct 26 '14 at 01:19
- 
                    @Keppil basically i want to round the number to the next floating number with 1 number after the ., for example '2.444424' to '2.5', '5.66764' to '5.7' – Matheus Fróes Oct 26 '14 at 01:42
- 
                    You have not answered my question yet; it has a huge impact on the answer you seek – fge Oct 26 '14 at 01:44
- 
                    @fge It's a `double` `double a = (n1 * 4) - 60; Double b = (a * -1) / 6; cp_nota2.setText(b + "");` – Matheus Fróes Oct 26 '14 at 01:54
2 Answers
3
            
            
        You have a few options, you might use a DecimalFormat, or a BigDecimal or even a String.format() like
double v = 3.4666666666663;
NumberFormat nf = new DecimalFormat("#.0");
System.out.println(nf.format(v));
MathContext mc = new MathContext(2);
System.out.println(BigDecimal.valueOf(v).round(mc));
System.out.printf("%.1f%n", v);
Output is
3.5
3.5
3.5
 
    
    
        Elliott Frisch
        
- 198,278
- 20
- 158
- 249
- 
                    Should be mentioned, that the first and the third method use the locale specific decimal seperator. – ifloop Oct 26 '14 at 01:27
-1
            
            
        Why don't you multiply it by 10, round that up, then divide by 10.
 
    
    
        logicOnAbstractions
        
- 2,178
- 4
- 25
- 37