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
  •  | 
  •  

문제

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,

도움이 되었습니까?

해결책

double myRoundedDoubleValue = Math.round(myValue);

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top