如何仅将字节值转换为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
$factorto pick units, we hardcode the conversion to GB: dividing by1024^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
相关产品推荐
相关产品推荐

