webmcp

diff framework/env/format/percentage.lua @ 0:9fdfb27f8e67

Version 1.0.0
author jbe/bsw
date Sun Oct 25 12:00:00 2009 +0100 (2009-10-25)
parents
children
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/framework/env/format/percentage.lua	Sun Oct 25 12:00:00 2009 +0100
     1.3 @@ -0,0 +1,35 @@
     1.4 +--[[--
     1.5 +text =                             -- text with the value formatted as a percentage
     1.6 +format.percentage(
     1.7 +  value,                           -- a number, a fraction or nil
     1.8 +  {
     1.9 +    nil_as        = nil_text       -- text to be returned for a nil value
    1.10 +    digits        = digits,        -- digits before decimal point (of the percentage value)
    1.11 +    precision     = precision,     -- digits after decimal point (of the percentage value)
    1.12 +    decimal_shift = decimal_shift  -- divide the value by 10^decimal_shift (setting true uses precision + 2)
    1.13 +  }
    1.14 +)
    1.15 +
    1.16 +Formats a number or fraction as a percentage.
    1.17 +
    1.18 +--]]--
    1.19 +
    1.20 +function format.percentage(value, options)
    1.21 +  local options = table.new(options)
    1.22 +  local f
    1.23 +  if value == nil then
    1.24 +    return options.nil_as or ""
    1.25 +  elseif atom.has_type(value, atom.number) then
    1.26 +    f = value
    1.27 +  elseif atom.has_type(value, atom.fraction) then
    1.28 +    f = value.float
    1.29 +  else
    1.30 +    error("Value passed to format.percentage(...) is neither a number nor a fraction nor nil.")
    1.31 +  end
    1.32 +  options.precision = options.precision or 0
    1.33 +  if options.decimal_shift == true then
    1.34 +    options.decimal_shift = options.precision + 2
    1.35 +  end
    1.36 +  local suffix = options.hide_unit and "" or " %"
    1.37 +  return format.decimal(f * 100, options) .. suffix
    1.38 +end

Impressum / About Us