-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblStringToNumberConversions.hpp
More file actions
960 lines (767 loc) · 27.5 KB
/
blStringToNumberConversions.hpp
File metadata and controls
960 lines (767 loc) · 27.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
#ifndef BL_STRINGTONUMBERCONVERSIONS_HPP
#define BL_STRINGTONUMBERCONVERSIONS_HPP
///-------------------------------------------------------------------
///
///
///
/// PURPOSE: A collection of simple functions to
/// convert strings to numbers and to
/// some blMathAPI structures
///
/// AUTHOR: Vincenzo Barbato
/// navyenzo@gmail.com
///
/// NOTE: All things in this library are defined within the
/// blMathAPI namespace
///
/// LISENSE: MIT-LICENCE
/// http://www.opensource.org/licenses/mit-license.php
///
///
///
///-------------------------------------------------------------------
//-------------------------------------------------------------------
// Includes needed for this file
//-------------------------------------------------------------------
#include "blNumericFunctions.hpp"
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// NOTE: This class is defined within the blMathAPI namespace
//-------------------------------------------------------------------
namespace blMathAPI
{
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Count the number of characters that an
// integer is going to need when we convert
// it to a string
//-------------------------------------------------------------------
template<typename blIntegerType>
inline int countIntToStringLength(blIntegerType number)
{
int count = 0;
if(number < 0)
{
// In this case, we
// return the number
// of characters of the
// positive integer plus
// one needed for the
// negative sign
++count;
}
if(number < 10)
return 1 + count;
while(number > 0)
{
++count;
number /= 10;
}
return count;
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Count the number of leading zeros after
// the decimal point in a floating point
// number
//-------------------------------------------------------------------
template<typename blNumberType>
inline int countLeadingDecimalZerosInFloatingPointNumber(blNumberType number,
const int& precision)
{
if(number == 0)
return 0;
if(number < 0)
return countLeadingDecimalZerosInFloatingPointNumber(-number,precision);
int count = 0;
number *= blNumberType(10);
while( number < 1 &&
(count < precision) )
{
number *= blNumberType(10);
++count;
}
return count;
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Count the number of characters that a
// floating point number is going to need
// when we convert it to a string using the
// specified decimal precision
//-------------------------------------------------------------------
template<typename blNumberType>
inline int countFloatingPointToStringLength(const blNumberType& number,
const int& precision,
const bool& shouldLeadingZeroBeCounted)
{
// We return the
// count of digits
// needed by the
// integral part of
// the number plus
// the point delimiter
// plus the specified
// precision
if(number < 0)
return ( countFloatingPointToStringLength(-number,precision,shouldLeadingZeroBeCounted) + 1);
if(number < 1 &&
!shouldLeadingZeroBeCounted)
{
// In this case
// we don't want
// to count the
// zero right before
// the decimal point
if(precision > 0)
return ( countIntToStringLength(number) + precision );
else
return ( countIntToStringLength(number) );
}
else
{
if(precision > 0)
return ( countIntToStringLength(number) + 1 + precision );
else
return ( countIntToStringLength(number) );
}
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Count the number of characters that a
// floating point number is going to need
// when we convert it to a string using the
// specified decimal precision and using
// scientific notation
//-------------------------------------------------------------------
template<typename blNumberType>
inline int countFloatingPointToStringLengthUsingScientificNotation(const blNumberType& number,
const int& precision,
const bool& shouldLeadingZeroBeCounted)
{
// Using "Normalized"
// scientific notation
// the number will
// look like: X.XXXeYYY
// That means that the
// number of digits needed
// are going to be:
// 0 or 1 -- For negative sign
// 1 -- For the integral part
// 1 -- For the decimal point
// delimiter
// Precision -- For the decimal part
// 1 -- For the 'e' indicating
// the exponent
// N -- For the exponent
int digitsNeededForExponent;
if(number > 0)
{
digitsNeededForExponent = countIntToStringLength( countIntToStringLength(number) / 10 );
if(number < 1 &&
!shouldLeadingZeroBeCounted)
{
return ( digitsNeededForExponent + 2 + precision);
}
else
return ( digitsNeededForExponent + 3 + precision);
}
else
return ( countFloatingPointToStringLengthUsingScientificNotation(-number,precision,shouldLeadingZeroBeCounted) + 1 );
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Convert an integer to a string, where the
// the number will be converted in reverse
// order.
//
// The function will return an iterator
// to the place in the string after the
// last place that it wrote to.
//-------------------------------------------------------------------
template<typename blIntegerType,
typename blStringIteratorType>
inline blStringIteratorType intToString(blIntegerType number,
const blIntegerType& base,
blStringIteratorType beginReverseIter,
const blStringIteratorType& endReverseIter)
{
if(beginReverseIter == endReverseIter)
return beginReverseIter;
if(number < 0)
{
beginReverseIter = intToString(-number,
base,
beginReverseIter,
endReverseIter);
if(beginReverseIter != endReverseIter)
{
(*beginReverseIter) = '-';
++beginReverseIter;
return beginReverseIter;
}
}
else if(number == 0)
{
(*beginReverseIter) = '0';
++beginReverseIter;
}
else
{
while( static_cast<uint64_t>(number) > 0 &&
beginReverseIter != endReverseIter )
{
(*beginReverseIter) = (static_cast<uint64_t>(number) % base) + '0';
++beginReverseIter;
number /= base;
}
}
return beginReverseIter;
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Convert an integer to a string, where the
// the number will be converted in reverse
// order.
//
// The function will return an iterator
// to the place in the string after the
// last place that it wrote to.
//-------------------------------------------------------------------
template<typename blFloatingPointType,
typename blStringIteratorType>
inline blStringIteratorType floatingPointToString(blFloatingPointType number,
const int& precision,
blStringIteratorType beginReverseIter,
const blStringIteratorType& endReverseIter,
const bool& shouldLeadingZeroBeCounted,
const bool& shouldLastDecimalDigitBeRounded = true)
{
// First, we separate
// the integral and
// fractional parts
// of the number
blFloatingPointType integralPart,fractionalPart;
fractionalPart = blMathAPI::modf(number,&integralPart);
if(precision > 0)
{
// Count the number of
// leading decimal
// zeros in the fractional
// part
int numberOfLeadingDecimalZeros = countLeadingDecimalZerosInFloatingPointNumber(fractionalPart,precision);
// Here we multiply
// the fractional part
// by 10^Precision to
// convert it to an
// integer
fractionalPart *= ( blMathAPI::power(double(10),double(precision)) );
// Check if last
// decimal digit
// needs to be
// rounded up
if( shouldLastDecimalDigitBeRounded &&
( (unsigned long long int)(fractionalPart) % 10 >= 5 ) )
{
++fractionalPart;
}
// And now we write
// the fractional part
// into the string
// (Making sure we
// convert it as a
// positive number and
// not negative
if(fractionalPart > 0)
beginReverseIter = intToString(fractionalPart,10,beginReverseIter,endReverseIter);
else
beginReverseIter = intToString(-fractionalPart,10,beginReverseIter,endReverseIter);
// Here we add the
// additional leading
// zeros if needed
int leadingDecimalZerosAddedSoFar = 0;
while( (leadingDecimalZerosAddedSoFar < numberOfLeadingDecimalZeros) &&
(beginReverseIter != endReverseIter) )
{
(*beginReverseIter) = '0';
++beginReverseIter;
++leadingDecimalZerosAddedSoFar;
}
// We then add the
// decimal point
// delimiter to
// the string
if(beginReverseIter != endReverseIter)
{
(*beginReverseIter) = '.';
++beginReverseIter;
}
}
// Finally, we convert
// the integral part
// to string
if( int(integralPart) == 0 &&
number < 0 &&
beginReverseIter != endReverseIter &&
!shouldLeadingZeroBeCounted)
{
// In this case, we
// just write the
// negative sign
(*beginReverseIter) = '-';
++beginReverseIter;
}
else
{
if(int(integralPart) != 0 ||
shouldLeadingZeroBeCounted)
{
beginReverseIter = intToString(integralPart,10,beginReverseIter,endReverseIter);
}
if( int(integralPart) == 0 &&
number < 0 &&
beginReverseIter != endReverseIter )
{
(*beginReverseIter) = '-';
++beginReverseIter;
}
}
return beginReverseIter;
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Convert an integer to a string, where the
// the number will be converted in reverse
// order.
//
// The function will return an iterator
// to the place in the string after the
// last place that it wrote to.
//-------------------------------------------------------------------
template<typename blFloatingPointType,
typename blStringIteratorType>
inline blStringIteratorType floatingPointToStringUsingScientificNotation(blFloatingPointType number,
const int& precision,
blStringIteratorType beginReverseIter,
const blStringIteratorType& endReverseIter,
const bool& shouldLastDecimalDigitBeRounded = true)
{
// First we check the
// integral part of
// the number
if(int(number) > 0 && int(number) < 10)
{
// In this case, the
// number is already
// expressed in "Normalized"
// scientific notation
return floatingPointToString(number,
precision,
beginReverseIter,
endReverseIter,
true,
shouldLastDecimalDigitBeRounded);
}
if(int(number) > 9)
{
int numberOfDigits;
if(number > 0)
numberOfDigits = countIntToStringLength(int(number));
else
numberOfDigits = countIntToStringLength(int(-number));
// The first thing we
// write to the string
// is the exponent
beginReverseIter = intToString(numberOfDigits - 1,
10,
beginReverseIter,
endReverseIter);
// We then write the "e"
// to the string
if(beginReverseIter != endReverseIter)
{
(*beginReverseIter) = 'e';
++beginReverseIter;
}
else
{
// Ran out of string
// length
return beginReverseIter;
}
// Next we normalize
// the number
number /= blMathAPI::power(blFloatingPointType(10),blFloatingPointType(numberOfDigits - 1));
// Finally we write
// the floating point
// to the string
return floatingPointToString(number,
precision,
beginReverseIter,
endReverseIter,
true,
shouldLastDecimalDigitBeRounded);
}
// If we've made it this
// far in the function then
// that means we have a
// number > 0 but < 1
// The first thing we do
// is count the number of
// leading zeros after
// the decimal point
int numberOfLeadingZeros = countLeadingDecimalZerosInFloatingPointNumber(number,precision);
// Next we write the
// exponent to the string
beginReverseIter = intToString(numberOfLeadingZeros + 1,
10,
beginReverseIter,
endReverseIter);
// We then write the "e"
// to the string
if(beginReverseIter != endReverseIter)
{
(*beginReverseIter) = 'e';
++beginReverseIter;
}
else
{
// Ran out of string
// length
return beginReverseIter;
}
// Next we normalize
// the number
number *= blMathAPI::power(blFloatingPointType(10),blFloatingPointType(numberOfLeadingZeros + 1));
// Finally we write
// the floating point
// to the string
return floatingPointToString(number,
precision,
beginReverseIter,
endReverseIter,
true,
shouldLastDecimalDigitBeRounded);
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Functions used to test whether a character
// is purely numeric, or numeric plus some accepted
// characters in a number such as the decimal point,
// plus sign, minus sign, exponent etc.
//-------------------------------------------------------------------
template<typename blCharacterType>
inline bool isCharNumeric(const blCharacterType& character)
{
return ( (character >= '0' && character <= '9')
|| character == '-'
|| character == '+'
|| character == '.');
}
template<typename blCharacterType>
inline bool isCharNumericPlus(const blCharacterType& character)
{
return ( (character >= '0' && character <= '9')
|| character == '-'
|| character == '+'
|| character == 'e'
|| character == 'E'
|| character == '.');
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// This function converts a sequence
// of characters to a number.
//
// The function returns an iterator
// to the place after the last character
// in the sequence that was used to
// determine the number.
//
// More clearly, it returns an iterator
// to the first non-valid character.
//-------------------------------------------------------------------
template<typename blStringIteratorType,
typename blCharacterType,
typename blNumberType>
inline blStringIteratorType convertStringToNumber(const blStringIteratorType& beginIter,
const blStringIteratorType& endIter,
const blCharacterType& decimalPointDelimiter,
blNumberType& convertedNumber,
const int& numberOfTimesToRepeatTheSearchIfBeginIterEqualsEndIter)
{
// First we check
// if the user
// passed a zero
// sized string
if(beginIter == endIter)
{
// In this case
// there's nothing
// to convert so we
// simply return
return endIter;
}
// Initialize the
// converted number
convertedNumber = blNumberType(0);
// Iterator used to
// parse the string
blStringIteratorType currentPos = beginIter;
// Boolean to check
// if the number is
// negative
bool isNumberNegative = false;
// Boolean and
// multiplier
// used to handle
// decimal point
// digits
bool hasDecimalPointBeenEncounteredAlready = false;
blNumberType decimalPointMultiplier = blNumberType(1);
// The first step
// is to check the
// first digit for
// special characters
if((*currentPos) == '-')
{
// This means the
// number is negative
isNumberNegative = true;
// Advance the position
++currentPos;
}
else if((*currentPos) == '+')
{
// This means the
// number is positive
// so we simply advance
// the position to the
// next character
++currentPos;
}
else if((*currentPos) == decimalPointDelimiter)
{
// This means the
// number starts with
// a decimal point
hasDecimalPointBeenEncounteredAlready = true;
++currentPos;
}
else if((*currentPos) == 'e' || (*currentPos) == 'E')
{
// In this case, the
// first character of
// the string is an 'e'
// or 'E', which means
// that the number is
// an exponent.
// Since it is the first
// character, then the
// number will be
// 10^Exponent.
// Therefore, we find
// the exponent and
// then raise 10
// to its power
++currentPos;
blNumberType exponent;
blStringIteratorType newPos = convertStringToNumber(currentPos,
endIter,
decimalPointDelimiter,
exponent,
numberOfTimesToRepeatTheSearchIfBeginIterEqualsEndIter - 1);
if(newPos == currentPos)
{
// We obviously
// had no exponent
// so we assume
// that it was e0
// or * 10^0, which
// means it is 1
convertedNumber = blNumberType(1);
return currentPos;
}
else
{
// In this case,
// we had a valid
// exponent
convertedNumber = blNumberType(blMathAPI::power(double(10),double(exponent)));
currentPos = newPos;
}
return currentPos;
}
// Keep track of how
// many times we go
// over the BeginIter
// in case of a circular
// iterator
int numberOfRepeats = 0;
// Now we loop through
// the remaining elements
// of the string and
// calculate the number
// accordingly.
// NOTE: Remember that we
// are looping from
// left to right, so
// from the highest
// digit to the lowest
// value digit (numerically
// speaking)
while((currentPos != endIter) &&
numberOfRepeats <= numberOfTimesToRepeatTheSearchIfBeginIterEqualsEndIter)
{
if((*currentPos) >= '0' && (*currentPos) <= '9')
{
// This means we
// have a valid
// numeric digit
if(hasDecimalPointBeenEncounteredAlready)
{
// This means that
// the digit is
// after the decimal
// point, so we add
// the current digit
// divided by its
// place after the
// decimal point
decimalPointMultiplier *= blNumberType(10);
convertedNumber = convertedNumber + blNumberType((*currentPos) - '0')/decimalPointMultiplier;
}
else
{
// This means that
// the digit is before
// the decimal point,
// so we multiply the
// current number by
// 10 and add the new
// digit
convertedNumber = convertedNumber * blNumberType(10) + blNumberType((*currentPos) - '0');
}
}
else if((*currentPos) == decimalPointDelimiter && !hasDecimalPointBeenEncounteredAlready)
{
// This means that
// we have just found
// the decimal point
// so we just store the
// fact that we found it
// in the boolean
hasDecimalPointBeenEncounteredAlready = true;
}
else if((*currentPos) == 'e' || (*currentPos) == 'E')
{
// In this case, it
// means that we're
// about to multiply
// the current number
// by 10^Exponent.
// Thus, we find the value of the
// exponent and then multiply
// First we move
// to the next
// position in the
// string (the one
// after the 'e' or 'E')
++currentPos;
// Then we calculate
// the exponent by
// recursively calling
// this function
blNumberType exponent;
blStringIteratorType newPos = convertStringToNumber(currentPos,
endIter,
decimalPointDelimiter,
exponent,
numberOfTimesToRepeatTheSearchIfBeginIterEqualsEndIter - numberOfRepeats);
if(newPos == currentPos)
{
// If the iterators
// are equal, that
// means that the
// function did not
// find a valid exponent.
// In this case, we
// assume the exponent
// was zero and we
// multiply the current
// number by 10^0,
// meaning multiply by 1.
// So we are done
break;
}
else
{
// In this case,
// we had a valid
// exponent, so
// we multiply the
// current number
// by 10^Exponent
convertedNumber = convertedNumber * blNumberType(blMathAPI::power(double(10),double(exponent)));
currentPos = newPos;
// We are done
break;
}
}
else
{
// In this case, we
// found a non-valid
// character, so we
// are done
break;
}
// Advance the
// iterator
++currentPos;
if(currentPos == beginIter)
++numberOfRepeats;
}
// Check if the number
// is negative
if(isNumberNegative)
convertedNumber *= blNumberType(-1);
// Now we return the
// current position
return currentPos;
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Convenient template functions to simplify the
// use of the string to number conversion function
//-------------------------------------------------------------------
template<typename blStringType,
typename blNumberType>
inline void convertStringToNumber(const blStringType& inputString,
blNumberType& outputNumber)
{
convertStringToNumber(inputString.begin(),
inputString.end(),
'.',
0);
}
template<typename blStringType>
inline int convertStringToInteger(const blStringType& inputString)
{
int result = -1;
convertStringToNumber(inputString,result);
return result;
}
template<typename blStringType>
inline double convertStringToDouble(const blStringType& inputString)
{
double result = -1;
convertStringToNumber(inputString,result);
return result;
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// End of the blMathAPI namespace
}
//-------------------------------------------------------------------
#endif // BL_STRINGTONUMBERCONVERSIONS_HPP