mnyfmt.c: Format money or currency amounts
str2mnyCE.c
Go to the documentation of this file.
1 // (C) Copyright Adolfo Di Mare 2011
2 // Use, modification and distribution are subject to the
3 // Boost Software License, Version 1.0.
4 // (See accompanying file LICENSE_1_0.txt or copy at
5 // http://www.boost.org/LICENSE_1_0.txt)
6 
7 // str2mnyCE.c (C) 2013 adolfo@di-mare.com
8 
9 // Define this macro if your compiler does not have a (long long) data type
10 // #define MNYFMT_NO_LONG_LONG
11 
12 #include "mnyfmt.h"
13 
14 #ifdef __cplusplus
15 // To compile the C source with a C++ compiler, override the file's extension.
16 // The GNU gcc compiler does this with option -x: gcc -x c++
17 #endif
18 
19 /** \file str2mnyCE.c
20  \brief Implementation for \c str2mnyCE().
21 
22  \author Adolfo Di Mare <adolfo@di-mare.com>
23  \date 2011
24 */
25 
26 /** Returns an integer value that corresponds to 'amount', scaled 10^CE digits.
27  - For " -102,455.87" returns '-102_455_8700' when CE==4 && dec=='.'.
28  - For " -102,455.07" returns '-102_455_07' when CE==2 && dec=='.'.
29  - For " -102,455.87" returns '-102_455' when CE==0 && dec=='.'.
30  - The decimal separator is 'dec'.
31  - CE is the 'currency exponent'.
32  - Requires 'CE<=6' <--> scale up to 10^6 <--> 6 decimal digits.
33 
34  \dontinclude mnyfmtts.c
35  \skipline test::str2mnyCE()
36  \until }}
37 
38  \see str2mnyCE.c
39 */
40 mnyfmt_long str2mnyCE( const char * amount , char dec , unsigned CE ) {
41  #ifndef isdigit
42  #define isdigit(ch) ('0'<=(char)(ch) && (char)(ch)<='9')
43  #define remove_isdigit
44  #endif
45  static mnyfmt_long TENPOW[6+1] = { 1,10,100,1000,10000,100000,1000000 };
46  if ( CE>(-1+sizeof(TENPOW)/sizeof(*TENPOW)) ) { return 0; }
47 
48  const char *p = amount; // " -102,455.87"
49  int isNegative = 0; // false
50  while ( (*p!=0) && !isdigit(*p) && *p!=dec ) { isNegative = (*p=='-'); ++p; }
51  if ( *p==0 ) { return 0; }
52 
53  mnyfmt_long nInt = 0;
54  while ( *p!=0 && *p!=dec ) {
55  if ( isdigit(*p) ) { nInt = nInt*10 + (*p-'0'); }
56  ++p;
57  }
58 
59  mnyfmt_long nFrac = 0;
60  if ( *p!=0 ) { ++p; } // skip 'dec'
61  unsigned i;
62  for ( i=0; i<CE; ++i ) {
63  nFrac = nFrac*10;
64  if ( isdigit(*p) ) { nFrac += (*p-'0'); ++p; }
65  else { /* nada -- nothing */ }
66  }
67 
68  nInt = nInt * TENPOW[CE] + nFrac;
69  if ( isNegative ) { nInt = -nInt; }
70  return nInt;
71 
72  #ifdef remove_isdigit
73  #undef isdigit
74  #endif
75  #undef remove_isdigit
76 }
77 
78 // EOF: str2mnyCE.c
#define isdigit(ch)
Header file for mnyfmt().
long long mnyfmt_long
Definition: mnyfmt.h:17
mnyfmt_long str2mnyCE(const char *amount, char dec, unsigned CE)
Returns an integer value that corresponds to 'amount', scaled 10^CE digits.
Definition: str2mnyCE.c:40