Smart Formatting

Prev Next

Introduction

In various cases, the type of the original value may not be the same all time, or you want to apply different formatting instructions depending on the values contained. The approach is easy: In the 2nd function parameter, provide a 2-level nested parameter set which contains 1 or more formatting instructions for the different types and values.

Example: str( 123.45, { { numeral, "#,##0.00", en_US }, { string, "XXXXXXXXX", align right } } );

The first set of parameters is used if the value provided is a numeral. Otherwise, if it is a string, then the 2nd set of parameers will be used. A simple formatting approach will used if a type is encountered but not described, e.g. a boolean type in the example shown above.

Smart Formatting Conditions

The formatting conditions depend on the type of data provided, and optionally on the value.

Formatting Condition Description
string Data type is a string
blank string Data type is a string and the contents are blank
void Data type is a void. (Note: Format voids as strings)
numeral Data type is a numeral
positive Data type is a numeral, value is greater than 0
negative Data type is a negative value is smaller than 0
zero Data type is a numeral, value equals to 0
near zero Data type is a numeral, value equals or is very close to 0 (ruled by epsilon value)
date Data type is a date
blank date Data type is a date, containing a blank date
date time Data type is a date, containing both date and time
time Data type is a date, containing a time only
boolean Data type is a boolean
parameter set Data type is a parameter set+

In case you have different formats for positive (or negative) numbers and the rest, then desribe the formatting for the positive (or negative) numbers first because the checking is done from left to right.

  for all parameters( { 5678.91, 0, true, "Abc" }, v[] )
  {
      echo( str( v[], {
          { positive, "#,##0.0", de_ch },
          { string,  "x x x x", '', '-' },
          { numeral,  "0 'zero or negative'" },
          { boolean,  "'Boolean: ' TT" } } ) );
  }
5'678.9
0 zero or negative
Boolean:  TRUE
a b c -
Try it yourself: Open LIB_Features_smart_conversion_and_formatting.b4p in B4P_Examples.zip. Decompress before use.