Skip to content

Commit

Permalink
utils.floatToStr: 1. Add leftPaddingMethod option. 2. Stop trying to …
Browse files Browse the repository at this point in the history
…exclude the +/- sign from the beforeDecimal count; it's something that the layout writer should have in mind anyway, and the exclusion wasn't working unless 'signed' was specified. This could be a minor backward incompatibility.
  • Loading branch information
yoshifan committed Oct 6, 2018
1 parent c75064f commit 3d544f3
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -262,9 +262,13 @@ function utils.floatToStr(x, options)
if x == nil then return "nil" end
if options == nil then options = {} end

-- Guarantee at least a certain number of digits before the decimal
-- Guarantee at least a certain number of chars before the decimal
-- (+/- sign counts as 1 char)
local beforeDecimal = options.beforeDecimal or nil
-- Display a certain number of digits after the decimal
-- Method of padding the left side of the string: 'zero' or 'space'.
-- 'zero' is like '-00049.285'; 'space' is like ' -49.285'
local leftPaddingMethod = options.leftPaddingMethod or 'zero'
-- Display a certain number of chars after the decimal
local afterDecimal = options.afterDecimal or 3
-- Trim zeros from the right end
local trimTrailingZeros = options.trimTrailingZeros or false
Expand All @@ -274,16 +278,14 @@ function utils.floatToStr(x, options)
local f = "%"
if signed then f = f.."+" end
if beforeDecimal then
if signed then
-- The number after the 0 counts all digits + decimal point + sign
f = f.."0"..(beforeDecimal+afterDecimal+2)
else
-- The number after the 0 counts all digits + decimal point
f = f.."0"..(beforeDecimal+afterDecimal+1)
local totalChars = beforeDecimal + 1 + afterDecimal
if leftPaddingMethod == 'zero' then
f = f.."0"..totalChars
elseif leftPaddingMethod == 'space' then
f = f..totalChars
end
end
f = f.."."..afterDecimal.."f"

local s = string.format(f, x)

if trimTrailingZeros then
Expand Down Expand Up @@ -333,7 +335,7 @@ end
function utils.writeIntLE(address, value, numberOfBytesToWrite)
local remainingValue = value
local bytes = {}

for n = 1,numberOfBytesToWrite do
byteValue = remainingValue % 256
byteValue = tonumber(string.format("%.f", byteValue)) -- round to int
Expand Down

0 comments on commit 3d544f3

Please sign in to comment.