0

The follwoing equation & values give differnet outputs using Java/Javscript: Javascript:

var dayOfWeek = parseInt((dayOfMonth + 26 * (monthOfYear +1) / 10 + yearOfCentury + yearOfCentury / 4 + century / 4 + 5 * century) % 7);

Java:

int dayOfWeek = (dayOfMonth + 26 * (monthOfYear +1) / 10 + yearOfCentury + yearOfCentury / 4 + century / 4 + 5 * century) % 7; code here

If dayOfMonth =28, monthOfYear =7, yearOfCentury = 9, century=20

Java returns dayOfWeek = 3 (which is correct!) JS returns dayOfWeek = 4! (odd)

Any feedback appreciated.

2 Answers 2

2

That's because java is performing integer operations, as all variables have type int.

This code:

int dayOfMonth = 28, monthOfYear = 7, yearOfCentury = 9, century = 20;
int result = (dayOfMonth + 26 * (monthOfYear +1) / 10 + yearOfCentury + yearOfCentury / 4 + century / 4 + 5 * century) % 7;
System.out.println(result);

Outputs

3

Why?

Your operation means

(28 + 26*(7 + 1)/10 + 9 + 8/4 + 20/4 + 5 * 20) % 7.

If your variables are all ints, every result will be casted to int, so your expression would become

(28 + 20 + 9 + 2 + 5 + 100) % 7 = 164 % 7 = 3

26*(7 + 1)/10 is 20.8, but it's casted to int, so you will lose the decimal part.

But if you change the first two lines to

double dayOfMonth = 28, monthOfYear = 7, yearOfCentury = 9, century = 20;
double result = (dayOfMonth + 26 * (monthOfYear +1) / 10 + yearOfCentury + yearOfCentury / 4 + century / 4 + 5 * century) % 7;

The output will be

4.050000000000011

Which is the same output you have with javascript. Then you use the parseInt function (which in java is Integer.parseInt) so the final result will be 4

Sign up to request clarification or add additional context in comments.

2 Comments

Cheers, so changed the JS equation and got the correct output: var dayOfWeek = parseInt(parseInt(dayOfMonth + 26 * parseInt(monthOfYear +1) / 10 + yearOfCentury + parseInt(yearOfCentury / 4) + parseInt(century / 4) + parseInt(5 * century)) % 7); . Seems long way to go about to, is there are more effective way then breaking down each part of the expression with parseInt()?
@dancingbush I don't think there is, because javascript doesn't have types as java, everything is var, you can't declare an int, so it will treat double, int, etc as a generic number, without caring about integer division. I think you will always have floating point operations (if needed) if you don't use parseInt.
0

Re advice from backslash answer:

var dayOfWeek = parseInt(parseInt(dayOfMonth + 26 * parseInt(monthOfYear +1) / 10 + yearOfCentury + parseInt(yearOfCentury / 4) + parseInt(century / 4) + parseInt(5 * century)) % 7); .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.