Paste: locale snprintf

Author: Jon
Mode: factor
Date: Wed, 12 Aug 2015 22:25:38
Plain Text |
USING: alien.syntax alien.c-types byte-arrays math.parser.private locals ;
FUNCTION-ALIAS: mysnprintf-int int snprintf ( char* result, size_t size, c-string format, int d ) ;
FUNCTION-ALIAS: mysnprintf-float int snprintf ( char* result, size_t size, c-string format, double f ) ;

LIBRARY: libc 
CONSTANT: LC_NUMERIC 1
FUNCTION: c-string setlocale ( int category, c-string locale ) ;

: with-locale ( quot category locale -- )
  over f setlocale
  [ drop setlocale drop call ] [ nip setlocale drop ] 3bi ; inline

:: my-int-format ( n locale -- string )
 [
  100 dup <byte-array> [ swap "%'d" n mysnprintf-int drop ] keep
  dup 0 swap index format-head 
 ] LC_NUMERIC locale with-locale ;

1234123 "fr_FR.UTF-8" my-int-format print
1234123 "en_US.UTF-8" my-int-format print
! 1 234 123
! 1,234,123

Annotation: after FUNCTION: changes regarding ";"

Author: Jon
Mode: factor
Date: Thu, 13 Aug 2015 21:09:58
Plain Text |
USING: alien.syntax alien.c-types byte-arrays math.parser.private locals ;
FUNCTION-ALIAS: mysnprintf-int int snprintf ( char* result, size_t size, c-string format, int d )
FUNCTION-ALIAS: mysnprintf-float int snprintf ( char* result, size_t size, c-string format, double f )

LIBRARY: libc 
CONSTANT: LC_NUMERIC 1
FUNCTION: c-string setlocale ( int category, c-string locale )

: with-locale ( quot category locale -- )
  over f setlocale
  [ drop setlocale drop call ] [ nip setlocale drop ] 3bi ; inline

:: my-int-format ( n locale -- string )
 [
  100 dup <byte-array> [ swap "%'d" n mysnprintf-int drop ] keep
  dup 0 swap index format-head 
 ] LC_NUMERIC locale with-locale ;

1234123 "fr_FR.UTF-8" my-int-format print
1234123 "en_US.UTF-8" my-int-format print
! 1 234 123
! 1,234,123

New Annotation

Summary:
Author:
Mode:
Body: