Oposite of util.parse_energy(energy)
Posted: Sat Jul 27, 2019 12:36 pm
Hi,
util.parse_energy(energy) will revert a string to a value. While creating some localised_description with additional values, I came across the need of converting an int value to it's string value (localised version then). Bilka said, when finished I should ask to add this to the core game lualib.
The function:
Kind regards
lovely_santa
util.parse_energy(energy) will revert a string to a value. While creating some localised_description with additional values, I came across the need of converting an int value to it's string value (localised version then). Bilka said, when finished I should ask to add this to the core game lualib.
The function:
Code: Select all
local prefix = {
{"si-prefix-symbol-kilo"},
{"si-prefix-symbol-mega"},
{"si-prefix-symbol-giga"},
{"si-prefix-symbol-tera"},
{"si-prefix-symbol-peta"},
{"si-prefix-symbol-exa"},
{"si-prefix-symbol-zetta"},
{"si-prefix-symbol-yotta"}
}
function util.createPrefixedValue(value, localisedUnitSymbol, roundPresicion)
-- roundPresicion defaults to 0 (aka integer value)
local prefixIndex = 0
while (value > 1000 and prefixIndex < #prefix) do
value = value / 1000
prefixIndex = prefixIndex + 1
end
prefix = prefix[prefixIndex]
if roundPresicion then -- make sure it is an uint value
roundPresicion = math.floor(roundPresicion + 0.5)
roundPresicion = roundPresicion > 0 and roundPresicion or nil
end
return {"",
string.format(roundPresicion and "%."..roundPresicion.."f " or "%i ", value),
prefix or localisedUnitSymbol, prefix and localisedUnitSymbol or nil
}
end
- It will parse the value and add the correct prefix symbol (for example 1001 converts to 1k, while 500 will not have a prefix)
- The passed localisedUnitSymbol will add the unit to the value, can be hardcoded as well, could also be empty ("" or nil).
- Code probably will need to be converted to use _ instead of capitalized characters
Code: Select all
util.createPrefixedValue(123456789, {"si-unit-symbol-watt"})
=> ingame shows as "123 MW"
util.createPrefixedValue(123456789, "W", 3)
=> ingame shows as "123.456 MW"
util.createPrefixedValue(2/3, {"si-unit-symbol-watt"}, 3)
=> ingame shows as "0.667 W"
lovely_santa