2010-11-23 38 views
4

不是一個真正的問題,而是一種挑戰..PHP格式字節轉換爲Javascript

我有這個PHP函數,我總是使用,現在我需要它在Javascript中。

function formatBytes($bytes, $precision = 0) { 
    $units = array('b', 'KB', 'MB', 'GB', 'TB'); 
    $bytes = max($bytes, 0); 
    $pow = floor(($bytes ? log($bytes) : 0)/log(1024)); 
    $pow = min($pow, count($units) - 1); 
    $bytes /= pow(1024, $pow); 
    return round($bytes, $precision) . ' ' . $units[$pow]; 
} 

編輯:感謝的答覆我想出了更短,但沒有精確度(讓我知道,如果你有一些新的想法)

function format_bytes(size){ 
    var base = Math.log(size)/Math.log(1024); 
    var suffixes = ['b', 'KB', 'MB', 'GB', 'TB' , 'PB' , 'EB']; 
    return Math.round(Math.pow(1024, base - Math.floor(base)), 0) + ' ' + suffixes[Math.floor(base)]; 
} 
+0

然後,它使用JavaScript編寫。 – AndreKR 2010-11-23 16:03:15

+0

+1適用於縮短的表格。 – Orbling 2010-11-23 16:28:37

回答

0

測試:

function formatBytes(bytes, precision) 
{ 
    var units = ['b', 'KB', 'MB', 'GB', 'TB']; 
    bytes = Math.max(bytes, 0); 
    var pwr = Math.floor((bytes ? Math.log(bytes) : 0)/Math.log(1024)); 
    pwr = Math.min(pwr, units.length - 1); 
    bytes /= Math.pow(1024, pwr); 
    return Math.round(bytes, precision) + ' ' + units[pwr]; 
} 
1

認爲這是正確的,沒有測試它:

更新:必須解決它,因爲沒有默認的精度和我在最後一行,現在功能錯字。

function formatBytes(bytes, precision) { 
    var units = ['b', 'KB', 'MB', 'GB', 'TB']; 
    var bytes = Math.max(bytes, 0); 
    var pow = Math.floor((bytes ? Math.log(bytes) : 0)/Math.log(1024)); 
    pow = Math.min(pow, units.length - 1); 
    bytes = bytes/Math.pow(1024, pow); 
    precision = (typeof(precision) == 'number' ? precision : 0); 
    return (Math.round(bytes * Math.pow(10, precision))/Math.pow(10, precision)) + ' ' + units[pow]; 
} 
+0

你的回報將返回NaN – 2010-11-23 16:16:37