Convert bytes to mb with only two decimal places

I’m currently using readDir and Scratch to create a map of key-values for a folder full of pdfs I need to reference in a list generated from a CSV. (For reasons not worth explaining, I need the file size). I don’t have a problem pulling the size in bytes, but using div seems to round to the nearest whole number; what I’m hoping to do is something more like the following:

<!--all my scratch/readDir stuff that creates $pdfs as a map pdfname : size-->
{{$bytes := index $pdfs $fulldoc}}
<!--$bytes returns 1291546, which is A-okay -->
{{$megs := div $bytes 1000000}}
<!--$megs returns 1, but I want, ideally, 1.29-->

Essentially, I’m wondering how to get the equivalent of a JavaScript toFixed() result at the templating layer…

Any recommendations?

1 Like

Replacing 1000000 with 1000000.0 worked for me:

{{ $x := 1291546 }}
{{ printf "%.2f" (div $x 1000000.0) }}

By the way, I was stunned to discover that there’s a div function. It’s not in either documentation site.

-j

3 Likes

It’s actually in both, but this isn’t a knock on you. It’s probably a sign that I should break these up into individual files on the docs concept site:

https://hugodocs.info/functions/math

More importantly, thanks for the fix. It worked like a charm :smile: !!!

Perhaps it would be more correct to say that it’s not searchable in either set of docs. :slightly_smiling: I knew about add and sub because they were used in examples and themes, but not the rest.

I forget where I first picked up the floating-point denominator trick. It exists in several languages.

-j

1 Like