-3

I have been trying to do something simple with java floating point division, have read several articles on some minimal changes on values but nothing like I am having below.

This is the expected:

float f = 1789773f / 1000000f;
System.out.printf("\n%.2f", f);

Outputs: 1,79

This is what happens when I work with variables:

int CLOCK=1789773;
System.out.printf("\n%.2f", (float)CLOCK/(10^6));

Outputs: 13410,48

What is going on? I had to use the literal '1000000f' instead of 10^6 to make it work. Also, I thought that casting the one of the division elements with (float) would set everything as float and I would not end doing integer math.

  • For reference: `^` is the bitwise exclusive or opreator and belongs to the [bitwise operators](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html). – Turing85 Aug 21 '20 at 19:33

3 Answers3

3

10^6 is not a million. It's 12, because ^ is the bitwise xor operator rather than exponentiation.

Use 1e6f, or just 1000000f.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

Try using this instead :

int CLOCK = 1789773;
float fclock = (float) (CLOCK/(Math.pow(10,6)));
System.out.printf("\n%.2f", fclock);
Karam Mohamed
  • 843
  • 1
  • 7
  • 15
0
float CLOCK=1789773f;
System.out.printf("\n%.2f", CLOCK/Math.pow(10,6));

OR

int CLOCK=1789773;
System.out.printf("\n%.2f",(float) (CLOCK/Math.pow(10,6)));

Try to use Math.pow(10,6), it's working fine for me.

Sagar Gangwal
  • 7,544
  • 3
  • 24
  • 38