how can i convert kilobyte to GB - javascript

I have
size: 0.20800000000000002``` in KB
I need to convert the readable format of the GB
{size / 1000000} is used this
output: 2.08e7
but it is not correct in a readable format I need to set it to a proper readable format of GB

let size_gb = (size / 1000000).toFixed(2);
The toFixed(2) method formats the number to have two decimal

Usually, 0.20800000000000002 Kb would be 0 Gb in a readable format. because the result will be 0.0000002000008. however, if you want to show it in a decimal number you can use the .toFixed() function.
let size: 0.20800000000000002
let sizeGb = (size/1000000).toFixed(7) // for this scenario
// the output will be 0.0000002
or
let size: 0.20800000000000002
let sizeGb = (size/1000000).toFixed(2) // the output will be 0.00

What do you define as a "readable" format? The hundreths place (if necessary?)
This will convert your number UP to the hundreths place IF necessary:
let kb = 0.20800000000000002;
let gb = kb / 1000000;
let gbFormat = Math.round(((kb / 1000000) + Number.EPSILON) * 100) / 100;
console.log(gbFormat);

Related

Calculate the size of a base64 image in Kb, Mb

In build a small Javascript application. With this app you can take photos via the cam. The App temporarily stores images in the Browser localStorage as base64. Now I want the app to be told the amount of storage used. So how big the image is in KB.
Each character has 8 bits. And 8 bits are 1 byte. So you have the formula:
small Example
const base64Image = 'data;image/png;base64, ... ';
const yourBase64String =
base64Image.substring(base64Image.indexOf(',') + 1);
const bits = yourBase64String.length * 6; // 567146
const bytes = bits / 8;
const kb = ceil(bytes / 1000);
// in one Line
const kb = ceil( ( (yourBase64String.length * 6) / 8) / 1000 ); // 426 kb

convert mebibyte to gigabyte

How can I convert mebibyte to gigabyte? Currently I'm just converting from megabytes to gigabytes.
export function megabyteToGigabyte(n: number) {
return n / Math.pow(10, 3);
}
But what about mebibytes?
1 Gigabyte is approximately 954 mebibyte
So you can simply divide n by 954 to convert MiB to GB
function MebibyteToGigabyte(n){
return n / 953.674; // 953.674 is the exact number
}
Convert to bytes: 1 mebibyte = 1048576 bytes
Then convert to gigabytes: 1 gigabyte = 1000000000 bytes
This gives you:
const MiBToGB = n => n * 1048576 / 1000000000;
console.log(MiBToGB(1000)); // 1.048576
Mebibyte(MiB) is a binary, unit, defined as 2^20 or 1024^2 Bytes.
So, 1 MiB = 1,048,576 Bytes
Whereas, Gigabyte(GB) is a decimal unit, defined as 10^9 or 1000^3 Bytes.
That makes 1 GB = 1,000,000,000 Bytes
To convert n MiB to GB, we have to multiply n with 1,048,576 and divide with 1000,000,000
for e.g. 1 MiB to GB = 1 * 1,048,576 / 1000,000,000 = 0.001048576
From above, the simplest way will be to just multiply n with 0.001048576.

Convert exponential notation of number (e+) to 10^ in JavaScript

I have a script, where I can convert gigs to megs to kilobytes to bytes to bits.
After that it uses the .toExponential function to turn it into scientific notation.
But I want it to change into an exponent, instead of it being +e# I want it to be ^#, any way I can change it to print that way instead, if not, anyway I can alter the string to change +e to ^?
Code:
console.log('calculator');
const gigabytes = 192;
console.log(`gigabytes equals ${gigabytes}`);
var megabytes = gigabytes * 1000;
console.log(`megabytes = ${megabytes}`);
var kilabytes = megabytes * 1000;
console.log (`kilabytes = ${kilabytes}`);
bytes = kilabytes * 1000;
console.log(`bytes = ${bytes}`);
bites = bytes * 8;
console.log(`bites are equal to ${bites}`);
console.log (bites.toExponential());
You can use .replace:
const bytes = '1.536e+12'
console.log(convert(bytes))
const inputs = [
'1.536e+12',
'1.536e-12',
'123',
'-123',
'123.456',
'-123.456',
'1e+1',
'1e-1',
'0e+0',
'1e+0',
'-1e+0'
]
function convert(value) {
return value.replace(/e\+?/, ' x 10^')
}
inputs.forEach(i => console.log(convert(i)))
You can just replace e+ with ^ using replace
console.log('calculator');
const gigabytes = 192;
console.log(`gigabytes equals ${gigabytes}`);
var megabytes = gigabytes * 1000;
console.log(`megabytes = ${megabytes}`);
var kilabytes = megabytes * 1000;
console.log (`kilabytes = ${kilabytes}`);
bytes = kilabytes * 1000;
console.log(`bytes = ${bytes}`);
bites = bytes * 8;
console.log(`bites are equal to ${bites}`);
console.log (bites.toExponential().replace(/e\+/g, '^'));
Instead of using
console.log(bites.toExponential);
You may need to use
bites = bites.toExponential;
console.log(bites.replace(“e+”, “*10^”);
Hope this helped!

About the unit transfer into [B, Kb, Mb],I don't know how to use Math.log()

The code is as follows.
function formatBytes(bytes,decimals) {
if(bytes == 0) return '0 Byte';
var k = 1000; // or 1024 for binary
var dm = decimals + 1 || 3;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
But I don't know how to use Math.log().
Correct way to convert size in bytes to KB, MB, GB in Javascript
The Math.log() function returns the natural logarithm (base e) of a
number, that is
∀x>0,Math.log(x) = ln(x)= the unique y such that e^y=x
var i = Math.floor(Math.log(bytes) / Math.log(k));
i will be index of sizes
For example: bytes < 1000 => i = 0 because floor method rounds a number downward to its nearest integer.
Consider that the size units bytes, KB, MB, GB etc. are in successive powers of 1024, as in 1024^0, 1024^1, 1024^2 and so on.
So to know which unit to use for an arbitrary number of bytes, one needs to calculate the highest power of 1024 below it.
The integral part of a postive valued base 2 logarithm, ln2( bytes), is the power of two below it, so an easy way to obtain the power of 1024 below a number is to divide its base 2 logarithm by 10, since 1024 is 2^10, and take the integral part.
This yields a function
function p1024( n) { return Math.floor(Math.log2( n) / 10);}
to use as an index into the units abbreviation array.
The posted code is using mathematical knowledge that ln2( n) / 10 is equivalent to ln( n) / ln(1024), where ln is the natural logarithm function and ln2 is a function for base 2 logarithms.
In Javascript Math is a global object which is accessible to all javascript code. In Java you may need to import java.lang.Math or java.lang.* before use (not a Java expert here).

Converting large integer to 8 byte array in JavaScript

I'm trying to convert a large number into an 8 byte array in javascript.
Here is an IMEI that I am passing in: 45035997012373300
var bytes = new Array(7);
for(var k=0;k<8;k++) {
bytes[k] = value & (255);
value = value / 256;
}
This ends up giving the byte array: 48,47,7,44,0,0,160,0. Converted back to a long, the value is 45035997012373296, which is 4 less than the correct value.
Any idea why this is and how I can fix it to serialize into the correct bytes?
Since you are converting from decimal to bytes, dividing by 256 is an operation that is pretty easily simulated by splitting up a number in a string into parts. There are two mathematical rules that we can take advantage of.
The right-most n digits of a decimal number can determine divisibility by 2^n.
10^n will always be divisible by 2^n.
Thus we can take the number and split off the right-most 8 digits to find the remainder (i.e., & 255), divide the right part by 256, and then also divide the left part of the number by 256 separately. The remainder from the left part can be shifted into the right part of the number (the right-most 8 digits) by the formula n*10^8 \ 256 = (q*256+r)*10^8 \ 256 = q*256*10^8\256 + r*10^8\256 = q*10^8 + r*5^8, where \ is integer division and q and r are quotient and remainder, respectively for n \ 256. This yields the following method to do integer division by 256 for strings of up to 23 digits (15 normal JS precision + 8 extra yielded by this method) in length:
function divide256(n)
{
if (n.length <= 8)
{
return (Math.floor(parseInt(n) / 256)).toString();
}
else
{
var top = n.substring(0, n.length - 8);
var bottom = n.substring(n.length - 8);
var topVal = Math.floor(parseInt(top) / 256);
var bottomVal = Math.floor(parseInt(bottom) / 256);
var rem = (100000000 / 256) * (parseInt(top) % 256);
bottomVal += rem;
topVal += Math.floor(bottomVal / 100000000); // shift back possible carry
bottomVal %= 100000000;
if (topVal == 0) return bottomVal.toString();
else return topVal.toString() + bottomVal.toString();
}
}
Technically this could be implemented to divide an integer of any arbitrary size by 256, simply by recursively breaking the number into 8-digit parts and handling the division of each part separately using the same method.
Here is a working implementation that calculates the correct byte array for your example number (45035997012373300): http://jsfiddle.net/kkX2U/.
[52, 47, 7, 44, 0, 0, 160, 0]
Your value and the largest JavaScript integer compared:
45035997012373300 // Yours
9007199254740992 // JavaScript's biggest integer
JavaScript cannot represent your original value exactly as an integer; that's why your script breaking it down gives you an inexact representation.
Related:
var diff = 45035997012373300 - 45035997012373298;
// 0 (not 2)
Edit: If you can express your number as a hexadecimal string:
function bytesFromHex(str,pad){
if (str.length%2) str="0"+str;
var bytes = str.match(/../g).map(function(s){
return parseInt(s,16);
});
if (pad) for (var i=bytes.length;i<pad;++i) bytes.unshift(0);
return bytes;
}
var imei = "a000002c072f34";
var bytes = bytesFromHex(imei,8);
// [0,160,0,0,44,7,47,52]
If you need the bytes ordered from least-to-most significant, throw a .reverse() on the result.
store the imei as a hex string (if you can), then parse the string in that manner, this way you can keep the precision when you build the array. I will be back with a PoC when i get home on my regular computer, if this question has not been answered.
something like:
function parseHexString(str){
for (var i=0, j=0; i<str.length; i+=2, j++){
array[j] = parseInt("0x"+str.substr(i, 2));
}
}
or close to that whatever...

Categories

Resources