How can i round float to nearest whole number and then convert into double in JAVA?

StackOverflow https://stackoverflow.com/questions/23267747

  •  08-07-2023
  •  | 
  •  

Question

I have a float value

float myValue=5.1824203;
  • How can i round float to nearest whole number and then convert into double?
  • What is the best method to achieve this ?

Thanks,

Was it helpful?

Solution

double myRoundedDoubleValue = Math.round(myValue);

OTHER TIPS

Try it this way:

public static void main(String arguments[]) {
    float myValue=5.1824203f;
    int rounded = Math.round(myValue);
    System.out.println("as int: " + rounded);
    float floated = (float) rounded;
    System.out.println("as float: " + floated);
}

OUTPUT:

as int: 5
as float: 5.0
float myValue=5.1824203f;
double rounded = Math.round(myValue);

Please also note the difference in the float myValue initialization.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top