New test.
[libsub.git] / src / raw_convert.cc
1 /*
2     Copyright (C) 2014-2019 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include "raw_convert.h"
21 #include "locale_convert.h"
22 #include <boost/algorithm/string.hpp>
23
24 using std::string;
25
26 static
27 string
28 make_local (string v)
29 {
30         struct lconv* lc = localeconv ();
31         boost::algorithm::replace_all (v, ".", lc->decimal_point);
32         /* We hope it's ok not to add in thousands separators here */
33         return v;
34 }
35
36 /** @param v Numeric value as an ASCII string */
37 static
38 string
39 make_raw (string v)
40 {
41         struct lconv* lc = localeconv ();
42         /* thousands_sep may be . so remove them before changing decimal points */
43         boost::algorithm::replace_all (v, lc->thousands_sep, "");
44         boost::algorithm::replace_all (v, lc->decimal_point, ".");
45         return v;
46 }
47
48 template <>
49 int
50 sub::raw_convert (string v, int precision)
51 {
52         return locale_convert<int> (make_local(v), precision);
53 }
54
55 template <>
56 float
57 sub::raw_convert (string v, int precision)
58 {
59         return locale_convert<float> (make_local(v), precision);
60 }
61
62 template <>
63 string
64 sub::raw_convert (unsigned long v, int precision)
65 {
66         return make_raw (locale_convert<string>(v, precision));
67 }