Convert an integer into a float with decimal places

1

How can I do to transform a number:

5 In: 0.0005

10 in: 0.0010

I'm trying this way:

int numero = 5;
float numero2 = Math.abs(numero / 10000);

But it is returning me like this: 0,0

    
asked by anonymous 21.12.2017 / 18:17

1 answer

2

This is nothing more than a peculiarity of Java. When you display a value on the screen, the toString method of the object is implicitly called. In the documentation of this method there is the comment that when the magnitude of the value is less than 10 ^ -3 or greater than 10 ^ 7 the value will be displayed with scientific notation. This probably is to make your rendering more readable to humans, as it does not change in nothing runs the code (the value does not change).

In the documentation for System.out.println(float) it is said that its execution is a call to System.out.print(float) followed by System.out.println() . In turn, the method System.out.print(float) displays the value returned by String.valueOf(float) , which returns exactly the value returned by Float.toString . In the documentation for the System.out.printf method, the return will be the same as System.out.format ", which displays values according to the rules defined for Formatter ", where f is the format for a decimal value, without invoking the toString method. >

As the result of the expression is less than 10 ^ -3, it is presented as scientific notation, being 5.0E-4 , which is the equivalent for 0.0005 .

If you even want to display the value without scientific notation, you can display the value using the printf method, instead of println , setting the format %f :

float numero = 5;
float numero2 = numero / 10000;
System.out.printf("%f\n", numero2);  // 0.000500 

See working at Repl.it

    
21.12.2017 / 19:40