Method: HexaPDF::Type::AcroForm::JavaScriptActions.apply_af_number_format

Defined in:
lib/hexapdf/type/acro_form/java_script_actions.rb

.apply_af_number_format(value, action_string) ⇒ Object

Implements the JavaScript AFNumber_Format function and returns the formatted field value.

The argument value has to be the field’s value (a String) and action_string has to be the JavaScript action string.

The AFNumber_Format function assumes that the text field’s value contains a number (as a string) and formats it according to the instructions.

It has the form AFNumber_Format(no_of_decimals, separator_style, negative_style, currency_style, currency_string, prepend_currency) where the arguments have the following meaning:

no_of_decimals

The number of decimal places after the decimal point, e.g. for 3 it would result in 123.456.

separator_style

Defines which decimal separator and whether a thousands separator should be used.

Possible values are:

0

Comma for thousands separator, point for decimal separator: 12,345.67

1

No thousands separator, point for decimal separator: 12345.67

2

Point for thousands separator, comma for decimal separator: 12.345,67

3

No thousands separator, comma for decimal separator: 12345,67

negative_style

Defines how negative numbers should be formatted.

Possible values are:

0

With minus and in color black: -12,345.67

1

Just in color red: 12,345.67

2

With parentheses and in color black: (12,345.67)

3

With parentheses and in color red: (12,345.67)

currency_style

This argument is not used, should be 0.

currency_string

A string with the currency symbol, e.g. € or $.

prepend_currency

A boolean defining whether the currency string should be prepended (true) or appended (false).



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/hexapdf/type/acro_form/java_script_actions.rb', line 315

def apply_af_number_format(value, action_string)
  return [value, nil] unless (match = AF_NUMBER_FORMAT_RE.match(action_string))
  value = af_make_number(value)
  format = "%.#{match[:ndec]}f"
  text_color = 'black'

  currency_string = JSON.parse(match[:currency_string])
  format = (match[:prepend] == 'true' ? currency_string + format : format + currency_string)

  if value < 0
    value = value.abs
    case match[:neg_style]
    when '0' # MinusBlack
      format = "-#{format}"
    when '1' # Red
      text_color = 'red'
    when '2' # ParensBlack
      format = "(#{format})"
    when '3' # ParensRed
      format = "(#{format})"
      text_color = 'red'
    end
  end

  [af_format_number(value, format, match[:sep_style]), text_color]
end