hi , I have a requirement where i need to convert bytes to kilobytes.
I am doing this by dividing by data/1024.
But when i am again assigning it back by * 1024.I am getting different value.
Please suggest me a perfect way to convert bytes to kb and again reconvert the value back.
Roger lelu wrote:I am doing this by dividing by data/1024.
What are you storing the result in? Doubles have rounding errors. BigDecimal keeps the entire decimal value. Then when you multiply back, you get the original because no precision was lost.
Why do you want to store it in a double/BigDecimal? The number of bytes isn't a floating point number so it should be stored in an integer/long/BigInteger.
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Personally, i wouldn't convert back and forth. Store it one way. When you need the other one, calculate and use it, but keep the original value. Storing the data twice is (almost) always a bad idea. converting back and for and back again is bound to lead to errors.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Hmm, looking at the original post, I think a double has more than enough precision for this problem. I suspect the real problem was in how the division was performed in the first place, before it was stored as a double. Was the calculation performed like this?
Or was it performed like this?
The difference between the two may look minor, but it can make a big difference. (Hint: I am assuming "bytes" is an int or long here.) Can you figure out why it makes a difference?
(I also agree with Fred's comments. However, converting back and forth is a useful test to see how accurate the conversion is. If you can't get the right number, you're probably doing the conversion wrong.)