Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a long to decimal

Tags:

java

I've tried to look around for a solution to this, but I simply can't. I want to show the megabyte representation of a long that is calculated in bytes.

In Java, you got a method called length() that you can invoke on a file object. It will return the files size in bytes stored in a long. Now, I want to that long and turn it into megabytes rather than bytes. A file I am trying with got the size 161000 bytes. If I am not mistaken, that translates to 0.161 megabytes. So I would do bytes / 100000 and I would expect to get 0.161. The problem is that I don't.

If I go to my Windows Calculator, or any other calculator for that matter, the application can manage to show those 3 decimals. Why is it that I can't do this? I tried to store the result in a double, which just comes out as 0.0

EDIT: An answers has been found. Thanks to wrm:

long b = file.length(); double mb = (double) b / (1024 * 1024);

like image 494
OmniOwl Avatar asked May 14 '12 12:05

OmniOwl


People also ask

Can long contain decimal?

Long variables can hold numbers from -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807. Operations with Long are slightly slower than with Integer . If you need even larger values, you can use the Decimal Data Type.

Does long have decimals C#?

long is just a big integer, it has nothing past the decimal point.

How do you turn a string into a decimal?

Converting a string to a decimal value or decimal equivalent can be done using the Decimal. TryParse() method. It converts the string representation of a number to its decimal equivalent.


1 Answers

maybe a little code would clarify the problem but i think, you have some kind of implicit conversion going on. something like this should work:

double result = (double)myLongVal / 1024.0;
like image 118
wrm Avatar answered Oct 30 '22 01:10

wrm