Separation of integer types. Are the results predictable?

I have a 64-bit long one that I want to round to the nearest 10,000, so I make it simple:

long myLong = 123456789 long rounded = (myLong / 10000) * 10000; //rounded = 123450000 

This is similar to what I expect, but since I'm not 100% on the insides of how integer types are divided, I'm just a little worried that there may be situations where this does not work properly.

Will this work with very large numbers / extreme cases?

+1
source share
2 answers

Yes, it will work if no result, intermediate or otherwise, exceeds long.MaxValue .

To be explicit regarding your constants, you can use the L specifier at the end, for example. 123456789L .

For such simple calculations, I can suggest Pex from Microsoft ( http://research.microsoft.com/en-us/projects/pex/ ), which searches for edge cases and checks them. This is a simple example, but if you are building a lot of logic on the basis that you are not sure, this is a great tool.

+4
source

Yes it will work. The semantics of integer separation guarantee what you expect.

However, it may be useful to write several tests for your specific use case, including edge cases. It will reassure you.

+1
source

All Articles