1
How can I turn 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’s returning to me like this: 0.0
1
How can I turn 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’s returning to me like this: 0.0
2
This is nothing more than a peculiarity of Java. When you display a value on the screen, implicitly it is called the method toString
of the object. In documentation of this method there is the comment that when the magnitude of the value is less than 10 -3 or more than 10 7 the value will be displayed with scientific notation. This probably is to make your representation more readable to humans, since it does not change the execution of the code at all (the value does not change).
In the documentation of System.out.println(float)
it is said that his execution is a call to System.out.print(float)
followed by a System.out.println()
. In turn, the method System.out.print(float)
displays the value returned by String.valueOf(float)
, that returns exactly the value returned by Float.toString
. Already in the method documentation System.out.printf
there is that the return will be the same as System.out.format
, which displays the values according to the rules defined for the Formatter
, where f
is the format for a decimal value, without invoking the method toString
.
As the result of the expression is less than 10 -3, it is presented as scientific notation, leaving 5.0E-4
, which is the equivalent of 0.0005
.
If you really want to display the value without scientific notation, you can display the value using the method printf
, in place of println
, defining the format %f
:
float numero = 5;
float numero2 = numero / 10000;
System.out.printf("%f\n", numero2); // 0.000500
See working on Repl.it
Browser other questions tagged java
You are not signed in. Login or sign up in order to post.
Just divide by 1000, no?
– Felipe Avelar
Yes, as is the method itself?
– user92401
Just split normally...
var/1000
– Felipe Avelar
Ok, and how can I do with INT values of a column? Even if I put double in the method it returns me only 0,0 and the value in the column is 5
– user92401
Provide a [mcve] of your code, otherwise you will only get guesses.
– user28595
The problem is that you are declaring as Int and Integer does not accept numbers after the comma, try using float type
– Felipe Avelar
Ready I edited..
– user92401
Math.abs(numero / 10000f);
– user28595
Call me back 5.0E-4
– user92401
This result is right, this is scientific notation.
5.0E-4
is the same as5.0 * 10^-4
, which results in the value you want. If you want the numeral without notation, you need to use another type of data, such as Biginteger.– user28595
Okay, and how would you look with Biginteger?
– user92401