factor/extra/money/money.factor

35 lines
999 B
Factor
Raw Normal View History

2016-04-18 23:16:33 -04:00
! Copyright (C) 2008 Doug Coleman.
! See http://factorcode.org/license.txt for BSD license.
USING: grouping io kernel lexer math math.functions math.parser
namespaces sequences splitting ;
2008-02-11 17:21:59 -05:00
IN: money
SYMBOL: currency-token
char: $ currency-token set-global
2016-04-18 23:16:33 -04:00
2008-02-11 17:21:59 -05:00
: dollars/cents ( dollars -- dollars cents )
2017-01-25 19:44:25 -05:00
100 * 100 /mod round >integer ;
2008-02-11 17:21:59 -05:00
2016-04-18 23:16:33 -04:00
: format-money ( dollars cents -- string )
[ number>string ] bi@
[ <reversed> 3 group "," join <reversed> ]
[ 2 char: 0 pad-head ] bi* "." glue ;
2016-04-18 23:16:33 -04:00
: money>string ( number -- string )
dollars/cents format-money currency-token get prefix ;
2008-09-06 14:58:14 -04:00
2016-04-18 23:16:33 -04:00
: money. ( number -- ) money>string print ;
2008-02-11 17:21:59 -05:00
ERROR: not-an-integer x ;
2008-02-11 17:45:38 -05:00
2016-04-18 23:16:33 -04:00
: split-decimal ( str -- neg? dollars cents )
"." split1 [ "-" ?head swap ] dip ;
2008-02-11 17:45:38 -05:00
: parse-decimal ( str -- ratio )
2016-04-18 23:16:33 -04:00
split-decimal [ [ "0" ] when-empty ] bi@
[
[ dup string>number [ ] [ not-an-integer ] ?if ] bi@
2016-04-18 23:16:33 -04:00
] keep length 10^ / + swap [ neg ] when ;
2017-08-26 15:20:04 -04:00
SYNTAX: \decimal: scan-token parse-decimal suffix! ;