Converting Bytes to Gb with Exact Decimals in Sql Server [Duplicate]

The first 2 columns have data in bytes. I am trying to convert it from Bytes to GB. For some reason its not reflecting properly in Free Space Column

    select vmi.VMTotalMaxSize, vmi.VMTotalSize, 
CONVERT(decimal(10,2),) as [VMTotalMaxSize (GB)],
CONVERT(decimal(10,2),) as [VMTotalSize (GB)],
CONVERT(decimal(10,2),(vmi.VMTotalMaxSize-vmi.VMTotalSize)/1024/1024/1024) as [VMFreeSpace (GB)]
from tbl_WLC_VMInstance vmi

VM Total Max Size:375809638400, 268435456000, 214748364800
VMTotalSize: 375683809280, 62755176448, 74662805504
VMTotalMaxSize (GB): 350.00, 250.00, 200.00
VMTotalSize (GB):349.00, 58.00, 69.00   
VMFreeSpace (GB)0.00, 191.00, 130.00

It would nice to have the data with proper calculation. Thanks

3

Divide by 1024.0, not 1024 - otherwise, your result is converted to integer thus losing decimal precision.

2
Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest