我通过PHP得到this code以字节为单位隐藏大小。
现在我想使用JavaScript将这些尺寸转换为人类可读尺寸。我试图将此代码转换为JavaScript,如下所示:
function formatSizeUnits(bytes){
if (bytes >= 1073741824) { bytes = (bytes / 1073741824).toFixed(2) + " GB"; }
else if (bytes >= 1048576) { bytes = (bytes / 1048576).toFixed(2) + " MB"; }
else if (bytes >= 1024) { bytes = (bytes / 1024).toFixed(2) + " KB"; }
else if (bytes > 1) { bytes = bytes + " bytes"; }
else if (bytes == 1) { bytes = bytes + " byte"; }
else { bytes = "0 bytes"; }
return bytes;
}
这是正确的做法吗?有更简单的方法吗?
答案 0 :(得分:553)
由此:(source)
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};
注意:这是原始代码,请使用下面的固定版本。 Aliceljm 不再激活她复制的代码
现在,未修改的固定版本,以及ES6:(按社区)
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
现在,修正版: (由Stackoverflow社区提供,+由JSCompress缩小)
function formatBytes(a,b){if(0==a)return"0 Bytes";var c=1024,d=b||2,e=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],f=Math.floor(Math.log(a)/Math.log(c));return parseFloat((a/Math.pow(c,f)).toFixed(d))+" "+e[f]}
用法:
// formatBytes(bytes,decimals)
formatBytes(1024); // 1 KB
formatBytes('1024'); // 1 KB
formatBytes(1234); // 1.21 KB
formatBytes(1234, 3); // 1.205 KB
演示/来源:
function formatBytes(bytes,decimals) {
if(bytes == 0) return '0 Bytes';
var k = 1024,
dm = decimals <= 0 ? 0 : decimals || 2,
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
// ** Demo code **
var p = document.querySelector('p'),
input = document.querySelector('input');
function setText(v){
p.innerHTML = formatBytes(v);
}
// bind 'input' event
input.addEventListener('input', function(){
setText( this.value )
})
// set initial text
setText(input.value);
<input type="text" value="1000">
<p></p>
PS:根据需要更改k = 1000
或sizes = ["..."]
(位或字节)
答案 1 :(得分:36)
function formatBytes(bytes) {
if(bytes < 1024) return bytes + " Bytes";
else if(bytes < 1048576) return(bytes / 1024).toFixed(3) + " KB";
else if(bytes < 1073741824) return(bytes / 1048576).toFixed(3) + " MB";
else return(bytes / 1073741824).toFixed(3) + " GB";
};
答案 2 :(得分:22)
const units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
function niceBytes(x){
let l = 0, n = parseInt(x, 10) || 0;
if(n === 1) return '1 byte'
while(n >= 1024 && ++l){
n = n/1024;
}
//include a decimal point and a tenths-place digit if presenting
//less than ten of KB or greater units
return(n.toFixed(n < 10 && l > 0 ? 1 : 0) + ' ' + units[l]);
}
结果:
niceBytes(1) // 1 byte
niceBytes(435) // 435 bytes
niceBytes(3398) // 3.3 KB
niceBytes(490398) // 479 KB
niceBytes(6544528) // 6.2 MB
niceBytes(23483023) // 22 MB
niceBytes(3984578493) // 3.7 GB
niceBytes(30498505889) // 28 GB
niceBytes(9485039485039445) // 8.4 PB
答案 3 :(得分:12)
当与字节相关时,有两种实际方法来表示大小,它们是SI单位(10 ^ 3)或IEC单位(2 ^ 10)。还有JEDEC,但他们的方法含糊不清,令人困惑。我注意到其他示例有错误,例如使用KB而不是kB来表示千字节,因此我决定编写一个函数,使用当前接受的度量单位范围来解决每个案例。
最后有一个格式化位会使数字看起来更好(至少在我看来)如果它不适合你的目的,可以随意删除它。
享受。
// pBytes: the size in bytes to be converted.
// pUnits: 'si'|'iec' si units means the order of magnitude is 10^3, iec uses 2^10
function prettyNumber(pBytes, pUnits) {
// Handle some special cases
if(pBytes == 0) return '0 Bytes';
if(pBytes == 1) return '1 Byte';
if(pBytes == -1) return '-1 Byte';
var bytes = Math.abs(pBytes)
if(pUnits && pUnits.toLowerCase() && pUnits.toLowerCase() == 'si') {
// SI units use the Metric representation based on 10^3 as a order of magnitude
var orderOfMagnitude = Math.pow(10, 3);
var abbreviations = ['Bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
} else {
// IEC units use 2^10 as an order of magnitude
var orderOfMagnitude = Math.pow(2, 10);
var abbreviations = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
}
var i = Math.floor(Math.log(bytes) / Math.log(orderOfMagnitude));
var result = (bytes / Math.pow(orderOfMagnitude, i));
// This will get the sign right
if(pBytes < 0) {
result *= -1;
}
// This bit here is purely for show. it drops the percision on numbers greater than 100 before the units.
// it also always shows the full number of bytes if bytes is the unit.
if(result >= 99.995 || i==0) {
return result.toFixed(0) + ' ' + abbreviations[i];
} else {
return result.toFixed(2) + ' ' + abbreviations[i];
}
}
答案 4 :(得分:11)
这是一个单行:
val => ['Bytes','Kb','Mb','Gb','Tb'][Math.floor(Math.log2(val)/10)]
甚至:
val => 'BKMGT'[~~(Math.log2(val)/10)]
答案 5 :(得分:10)
您可以使用filesizejs库。
答案 6 :(得分:5)
使用按位运算将是更好的解决方案。试试这个
function formatSizeUnits(bytes)
{
if ( ( bytes >> 30 ) & 0x3FF )
bytes = ( bytes >>> 30 ) + '.' + ( bytes & (3*0x3FF )) + 'GB' ;
else if ( ( bytes >> 20 ) & 0x3FF )
bytes = ( bytes >>> 20 ) + '.' + ( bytes & (2*0x3FF ) ) + 'MB' ;
else if ( ( bytes >> 10 ) & 0x3FF )
bytes = ( bytes >>> 10 ) + '.' + ( bytes & (0x3FF ) ) + 'KB' ;
else if ( ( bytes >> 1 ) & 0x3FF )
bytes = ( bytes >>> 1 ) + 'Bytes' ;
else
bytes = bytes + 'Byte' ;
return bytes ;
}
答案 7 :(得分:4)
根据Aliceljm的回答,我在小数点后删除了0:
function formatBytes(bytes, decimals) {
if(bytes== 0)
{
return "0 Byte";
}
var k = 1024; //Or 1 kilo = 1000
var sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + " " + sizes[i];
}
答案 8 :(得分:2)
我最初使用@Aliceljm的答案来处理我正在处理的文件上传项目,但最近遇到的问题是文件为0.98kb
但被读为1.02mb
。这是我正在使用的更新代码。
function formatBytes(bytes){
var kb = 1024;
var ndx = Math.floor( Math.log(bytes) / Math.log(kb) );
var fileSizeTypes = ["bytes", "kb", "mb", "gb", "tb", "pb", "eb", "zb", "yb"];
return {
size: +(bytes / kb / kb).toFixed(2),
type: fileSizeTypes[ndx]
};
}
然后在添加文件之后调用上面的内容
// In this case `file.size` equals `26060275`
formatBytes(file.size);
// returns `{ size: 24.85, type: "mb" }`
当然,Windows将文件读取为24.8mb
,但我的精确度更高。
答案 9 :(得分:2)
function bytesToSize(bytes) {
var sizes = ['B', 'K', 'M', 'G', 'T', 'P'];
for (var i = 0; i < sizes.length; i++) {
if (bytes <= 1024) {
return bytes + ' ' + sizes[i];
} else {
bytes = parseFloat(bytes / 1024).toFixed(2)
}
}
return bytes + ' P';
}
console.log(bytesToSize(234));
console.log(bytesToSize(2043));
console.log(bytesToSize(20433242));
console.log(bytesToSize(2043324243));
console.log(bytesToSize(2043324268233));
console.log(bytesToSize(2043324268233343));
答案 10 :(得分:1)
此解决方案基于以前的解决方案,但同时考虑了度量和二进制单位:
function formatBytes(bytes, decimals, binaryUnits) {
if(bytes == 0) {
return '0 Bytes';
}
var unitMultiple = (binaryUnits) ? 1024 : 1000;
var unitNames = (unitMultiple === 1024) ? // 1000 bytes in 1 Kilobyte (KB) or 1024 bytes for the binary version (KiB)
['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']:
['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var unitChanges = Math.floor(Math.log(bytes) / Math.log(unitMultiple));
return parseFloat((bytes / Math.pow(unitMultiple, unitChanges)).toFixed(decimals || 0)) + ' ' + unitNames[unitChanges];
}
示例:
formatBytes(293489203947847, 1); // 293.5 TB
formatBytes(1234, 0); // 1 KB
formatBytes(4534634523453678343456, 2); // 4.53 ZB
formatBytes(4534634523453678343456, 2, true)); // 3.84 ZiB
formatBytes(4566744, 1); // 4.6 MB
formatBytes(534, 0); // 534 Bytes
formatBytes(273403407, 0); // 273 MB
答案 11 :(得分:1)
我在这里更新@Aliceljm答案。由于小数位对1,2位数字很重要,因此我将小数点后第一位并保留第一个小数位。对于3位数字,我将单位舍入并忽略所有小数位。
getMultiplers : function(bytes){
var unit = 1000 ;
if (bytes < unit) return bytes ;
var exp = Math.floor(Math.log(bytes) / Math.log(unit));
var pre = "kMGTPE".charAt(exp-1);
var result = bytes / Math.pow(unit, exp);
if(result/100 < 1)
return (Math.round( result * 10 ) / 10) +pre;
else
return Math.round(result) + pre;
}
答案 12 :(得分:0)
var SIZES = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
function formatBytes(bytes, decimals) {
for(var i = 0, r = bytes, b = 1024; r > b; i++) r /= b;
return `${parseFloat(r.toFixed(decimals))} ${SIZES[i]}`;
}
答案 13 :(得分:0)
这是向人类显示一个字节的方式:
function bytesToHuman(bytes, decimals = 2) {
// https://en.wikipedia.org/wiki/Orders_of_magnitude_(data)
const units = ["bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"]; // etc
let i = 0;
let h = 0;
let c = 1 / 1023; // change it to 1024 and see the diff
for (; h < c && i < units.length; i++) {
if ((h = Math.pow(1024, i) / bytes) >= c) {
break;
}
}
// remove toFixed and let `locale` controls formatting
return (1 / h).toFixed(decimals).toLocaleString() + " " + units[i];
}
// test
for (let i = 0; i < 9; i++) {
let val = i * Math.pow(10, i);
console.log(val.toLocaleString() + " bytes is the same as " + bytesToHuman(val));
}
// let's fool around
console.log(bytesToHuman(1023));
console.log(bytesToHuman(1024));
console.log(bytesToHuman(1025));
答案 14 :(得分:0)
我只想分享我的意见。我有这个问题,所以我的解决办法是这样。这会将较低的单位转换为较高的单位,反之亦然,只需提供参数toUnit
和fromUnit
export function fileSizeConverter(size: number, fromUnit: string, toUnit: string ): number | string {
const units: string[] = ['B', 'KB', 'MB', 'GB', 'TB'];
const from = units.indexOf(fromUnit.toUpperCase());
const to = units.indexOf(toUnit.toUpperCase());
const BASE_SIZE = 1024;
let result: number | string = 0;
if (from < 0 || to < 0 ) { return result = 'Error: Incorrect units'; }
result = from < to ? size / (BASE_SIZE ** to) : size * (BASE_SIZE ** from);
return result.toFixed(2);
}
我从here那里得到了主意
答案 15 :(得分:0)
function bytes2Size(byteVal){
var units=["Bytes", "KB", "MB", "GB", "TB"];
var kounter=0;
var kb= 1024;
var div=byteVal/1;
while(div>=kb){
kounter++;
div= div/kb;
}
return div.toFixed(1) + " " + units[kounter];
}
答案 16 :(得分:0)
const b2s=t=>{let e=Math.log2(t)/10|0;return(t/1024**(e=e<=0?0:e)).toFixed(3)+"BKMGP"[e]};
console.log(b2s(0));
console.log(b2s(123));
console.log(b2s(123123));
console.log(b2s(123123123));
console.log(b2s(123123123123));
console.log(b2s(123123123123123));
答案 17 :(得分:0)
来自@Aliceljm 的相同答案,但以“更具说教性”的方式。 谢谢! =D
function formatBytes(numBytes, decPlaces) {
/* Adjust the number of bytes informed for the most appropriate metric according
to its value.
Args:
numBytes (number): The number of bytes (integer);
decPlaces (Optional[number])): The number of decimal places (integer). If
it is "undefined" the value "2" will be adopted.
Returns:
string: The number adjusted together with the most appropriate metric. */
if (numBytes === 0) {
return "0 Bytes";
}
// NOTE: 1 KB is equal to 1024 Bytes. By Questor
// [Ref(s).: https://en.wikipedia.org/wiki/Kilobyte ]
var oneKByte = 1024;
// NOTE: Treats if the "decPlaces" is "undefined". If it is "undefined" the value
// "2" will be adopted. By Questor
if (decPlaces === undefined || decPlaces === "") {
decPlaces = 2;
}
var byteMtrcs = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
// Byte Metrics
// NOTE: Defines the factor for the number of bytes and the metric. By Questor
var mtrcNumbFactor = Math.floor(Math.log(numBytes) / Math.log(oneKByte));
// Metrics Number Factor
return parseFloat((numBytes / Math.pow(oneKByte, mtrcNumbFactor)).
toFixed(decPlaces)) + " " + byteMtrcs[mtrcNumbFactor];
}
答案 18 :(得分:0)
function getReadableByte(count, decimal=0, level=0) {
let unitList = ["Bytes", "KB", "MB", "GB", "TB", "PT"];
if(count >= 1024.0 && (level+1 < unitList.length)) {
return getReadableByte(count/1024, decimal, ++level)
}
return `${decimal ? (count).toFixed(decimal) : Math.round(count)}${unitList[level]}`
}
console.log(getReadableByte(120, 2))
function getReadableByte(count, decimal=0, level=0) { let unitList = ["Bytes", "KB", "MB", "GB", "TB", "PT"];
if(count >= 1024.0 && (level+1 < unitList.length)) {
return getReadableByte(count/1024, decimal, ++level)
}
return `${decimal ? (count).toFixed(decimal) : Math.round(count)}${unitList[level]}`
}
console.log(getReadableByte(120, 2))
答案 19 :(得分:0)
这对我有用。
bytesForHuman(bytes) {
let units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
let i = 0
for (i; bytes > 1024; i++) {
bytes /= 1024;
}
return bytes.toFixed(1) + ' ' + units[i]
}
答案 20 :(得分:-4)
尝试这个简单的解决方法。
var files = $("#file").get(0).files;
var size = files[0].size;
if (size >= 5000000) {
alert("File size is greater than or equal to 5 MB");
}