I have a html table that lists data from data from a database. One of the entries is the file size in bytes. I want to display the value in the appropriate kb/mb/gb values.
I found a script here to make the conversion.
Below is my attempt at implementing the script, however it is not working.
The desired end state is to have a value like 3597671 Bytes display as 3.43 MB.
<script>
function SizeSuffix(a, b = 2, k = 1024) { with (Math) { let d = floor(log(a) / log(k)); return 0 == a ? "0 Bytes" : parseFloat((a / pow(k, d)).toFixed(max(0, b))) + " " + ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"][d] } }
function setSize(size, id) {
document.getElementById(id).innerText = SizeSuffix(size);
}
window.onload = function () {
var sizedata = document.getElementsByName("Size");
for (size in sizedata) {
bytes = size.innerText;
setSize(bytes, size.id);
}
}
</script>
@foreach (var History in Model)
{
<tr>
<td>@History.Date</td>
<td>@History.Path</td>
<td>@History.File</td>
<td name="Size" id="@History.Id">@History.FileSize</td>
</tr>
}
EDIT: I came up with a different solution. I am working with a partial view in razor pages. What I've done is pass the page model of the page that calls the partial view. I included a function in that page model that performs the transformation.
I replaced the line
<td name="Size" id="@History.Id">@History.FileSize</td>
with
<td>@Model.SizeSuffix((ulong)History.FileSize)</td>
and removed the script block. This performs the calculation when ever the partial view is loaded and supports the infinite scrolling code.