-
Star
(208)
You must be signed in to star a gist -
Fork
(34)
You must be signed in to fork a gist
-
-
Save thomseddon/3511330 to your computer and use it in GitHub Desktop.
app.filter('bytes', function() { | |
return function(bytes, precision) { | |
if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) return '-'; | |
if (typeof precision === 'undefined') precision = 1; | |
var units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'], | |
number = Math.floor(Math.log(bytes) / Math.log(1024)); | |
return (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision) + ' ' + units[number]; | |
} | |
}); |
Thanks !!!
if you wanna handle zero values as well and display them, change the 6th line like so:
number = Math.floor(Math.log(bytes) / Math.log(1024)) | 0;
Awesome!! +1
You just saved me 15 mins of my life
Very nice! Thanks !!!
Awesome! Thanks!
Thank you!!
Perfect. Thanks!!!
if you wanna change dot to comma as decimal separator, just simply add:
.replace('.', ',')
Here is the complete 7th line:
return (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision).replace('.', ',') + ' ' + units[number];
Thank you so much , very helpful 👍
what if bytes size is 0.025
Here it is for Angular ( I just formatted this up a bit, am using Angular7) - I did not port in the Unit Tests, but didn't modify the values, so, might be able to Angularize those as well
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'byteFormatter'
})
export class ByteFormatterPipe implements PipeTransform {
transform(bytes: string | number, precision: number): any {
if (isNaN(parseFloat(bytes.toString())) || !isFinite(Number(bytes))) {
return '-';
}
if (typeof precision === 'undefined') {
precision = 1;
}
const units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];
const actualValue = Math.floor(Math.log(Number(bytes)) / Math.log(1024));
return (Number(bytes) / Math.pow(1024, Math.floor(actualValue))).toFixed(precision) + ' ' + units[actualValue];
}
}
I don't know which OS you are referring to, @tamas-marton, but this is certainly not true in Windows. I just verified that both win7 and win10 uses 1024 as base for their units ;-)