The preference/option/map tools window allows you to modify the units of measurement. my QGIS v 3.22 is set to meters. I made a measurement. Then I finally wanted to do this calculation in kilometers without doing any division. So I configured QGIS in kilometers. The new calculation gives an identical result.
I don't understand where the problem comes from. Does someone have an idea?
sum($length) / 1000
will give you the km value in a meter projected layer.