You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅将字节值转换为GB而非KB/MB(适配ChartJS)

Force Byte Conversion to GB Only for ChartJS

Got it, let's tweak your function to always return values in GB—perfect for ChartJS where consistent units are key! Your original code automatically picks the "best" unit (like KB/MB), but we can simplify it to lock in GB exclusively.

Modified Function

function formatBytesToGB($size) {
    // Convert bytes directly to GB (1 GB = 1024^3 bytes)
    $gbValue = $size / pow(1024, 3);
    // Format to 2 decimal places and append GB unit
    return number_format($gbValue, 2) . " GB";
}

How It Works

  • Instead of calculating a dynamic $factor to pick units, we hardcode the conversion to GB: dividing by 1024^3 (since 1GB = 1024MB, 1MB=1024KB, 1KB=1024B).
  • number_format($gbValue, 2) ensures you get a clean, consistent 2-decimal output which works great for ChartJS data labels or tooltips.

Example Outputs

  • Input: 1073741824 (1GB) → Output: 1.00 GB
  • Input: 536870912 (512MB) → Output: 0.50 GB
  • Input: 1024 (1KB) → Output: 0.00 GB

This keeps all your data in the same unit, so ChartJS can render a smooth, easy-to-read scale without unit inconsistencies.

内容的提问来源于stack exchange,提问作者Raymond Clayton Rudman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:41:40