File: cgnumber_formatter.pro

package info (click to toggle)
coyote 2019.01.29-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 6,316 kB
  • sloc: python: 184; makefile: 14; sh: 13
file content (279 lines) | stat: -rw-r--r-- 12,242 bytes parent folder | download | duplicates (3)
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
; docformat = 'rst'
;
; NAME:
;   cgNumber_Formatter
;
; PURPOSE:
;   This is a utility routine format a number into a string. It is used primarily for 
;   formatting numbers that will appear in text widgets in widget programs.
;
;******************************************************************************************;
;                                                                                          ;
;  Copyright (c) 2012, by Fanning Software Consulting, Inc. All rights reserved.           ;
;                                                                                          ;
;  Redistribution and use in source and binary forms, with or without                      ;
;  modification, are permitted provided that the following conditions are met:             ;
;                                                                                          ;
;      * Redistributions of source code must retain the above copyright                    ;
;        notice, this list of conditions and the following disclaimer.                     ;
;      * Redistributions in binary form must reproduce the above copyright                 ;
;        notice, this list of conditions and the following disclaimer in the               ;
;        documentation and/or other materials provided with the distribution.              ;
;      * Neither the name of Fanning Software Consulting, Inc. nor the names of its        ;
;        contributors may be used to endorse or promote products derived from this         ;
;        software without specific prior written permission.                               ;
;                                                                                          ;
;  THIS SOFTWARE IS PROVIDED BY FANNING SOFTWARE CONSULTING, INC. ''AS IS'' AND ANY        ;
;  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES    ;
;  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT     ;
;  SHALL FANNING SOFTWARE CONSULTING, INC. BE LIABLE FOR ANY DIRECT, INDIRECT,             ;
;  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED    ;
;  TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;         ;
;  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND             ;
;  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT              ;
;  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS           ;
;  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                            ;
;******************************************************************************************;
;
;+
; This is a utility routine format a number into a string. It is used primarily for 
; formatting numbers that will appear in text widgets in widget programs.
;
; :Categories:
;    Utilities
;    
; :Returns:
;    A string with the formatted number or numbers is returned.
;    
; :Params:
;    number: in, required
;       The number to be turned into a string. May be any data type except complex, 
;       double complex, pointer or object. May be an array of numbers.
;       
; :Keywords:
;    decimals: in, optional, type=integer, default=2
;        Set this keyword to the number of decimal places to be included to the right of 
;        the decimal point in floats and doubles. Set to 2 by default. In numbers with
;        absolute values between 0 and 1, the number of decimals is equivalent to the
;        number of significant digits. See the example below.
;         
; :Examples:
;    Here is how to use this program::
;        IDL> array = [45.123456, -30.123456, !Values.F_Nan, !Values.F_Infinity, $
;                      0.00123456, -0.00123456, 0.0123456, 0.123456, 1.234567]
;        IDL> FOR j=0,N_Elements(array)-1 DO Print, Number_Formatter(array[j], Decimals=4)
;        45.1235
;        -30.1235
;        NaN
;        Inf
;        0.001235
;        -0.001235
;        0.01235
;        0.1235
;        1.2346
;       
; :Author:
;    FANNING SOFTWARE CONSULTING::
;       David W. Fanning 
;       1645 Sheely Drive
;       Fort Collins, CO 80526 USA
;       Phone: 970-221-0438
;       E-mail: david@idlcoyote.com
;       Coyote's Guide to IDL Programming: http://www.idlcoyote.com
;
; :History:
;     Change History::
;        Written, 8 November 2012 by David W. Fanning from the retired Number_Formatter program.
;        The algorithm I was using for numbers between 0 and 1 used a LT in the Where function to
;            find an index. It appears this should have been a LE, instead. 11 Jan 2013. DWF.
;
; :Copyright:
;     Copyright (c) 2012, Fanning Software Consulting, Inc.
;-
FUNCTION cgNumber_Formatter, number, DECIMALS=decimals

   On_Error, 2


   IF N_Elements(number) EQ 0 THEN Message, 'A number must be passed as an argument to the function.'
   IF N_Elements(decimals) EQ 0 THEN decimals = 2
   
   ; If the number is a byte, convert it to an integer and return it.
   IF Size(number[0], /TNAME) EQ 'BYTE' THEN RETURN, StrTrim(String(Fix(number), Format='(I3)'),2)

   ; If the number is a string, trim it and return it directly.
   IF Size(number[0], /TNAME) EQ 'STRING' THEN RETURN, StrTrim(number,2)

   ; Number can be an array. Handle that here.
   numElements = N_Elements(number)
   retValue = StrArr(numElements)
   FOR j=0,numElements-1 DO BEGIN
   
      ; Is the number a NaN?
      IF ~Finite(number[j]) THEN BEGIN
         IF Finite(number[j], /NAN) THEN retValue[j] = 'NaN'
         IF Finite(number[j], /Infinity) THEN retValue[j] = 'Inf'
      ENDIF
      IF ~Finite(number[j]) THEN CONTINUE
      
      ; Is this a number between zero and 1? Then the number of decimals should
      ; be adjusted to save the number of significant decimals in the fractional part of this
      ; number. This works as long as the number of zeros in front of the first
      ; significant digits doesn't exceed the number of decimals points asked for
      ; and the "G" formatting doesn't push into exponetial territory.
      IF (Abs(number[j]) GT 0.0001) && (Abs(number[j]) LT 1.0) THEN BEGIN
          savedecimals = decimals
          exponents = 1. / 10.^Indgen(12)
          index = Where(exponents LE Abs(number[j]), count)
          IF count EQ 0 THEN thisIndex = 11 ELSE thisindex = index[0]
          decimals = ((thisindex-1) + decimals)
      ENDIF
      
      ; Is the number a negative value? Deal only with positive values, until the end.
      IF number[j] LT 0.0 THEN minus = 1 ELSE minus = 0
      theNumber = Abs(number[j])

      ; Do the appropriate thing.
      CASE Size(theNumber, /TNAME) OF

         'INT': retValue[j] = StrTrim(String(theNumber),2)

         'LONG': retValue[j] = StrTrim(String(theNumber),2)

         'FLOAT': BEGIN

            ; Format the number with G format.
            aString = StrTrim(String(theNumber, Format='(G)'), 2)

            ; Split the number into a whole part and a fractional part.
            parts = StrSplit(aString, '.', /Extract)
            IF N_Elements(parts) EQ 1 THEN parts = [parts, '0']
            parts[1] = StrTrim(parts[1],2)

            ; Does the fractional part have an E or a D in it?
            loc = StRegEx(parts[1], '[DE]')
            CASE loc OF

               -1: BEGIN ; No exponent.

                   ; Round to the number of decimals you want.
                   fracpart = StrTrim(Round(Double('1.' + parts[1]) * (10LL^decimals), /L64), 2)
                   IF StrMid(fracpart,0,1) EQ '2' THEN BEGIN
                     parts[0] = StrTrim(Long64(parts[0]) + 1, 2)
                   ENDIF
                   parts[1] = StrMid(fracpart, 1)
                   retValue[j] = StrTrim(parts[0],2) + '.' + parts[1]
                   END

               ELSE: BEGIN

                   ; Divide the fractional part of the number up into parts.
                   ; Treat p[0] as you treated parts[1] above. Then put it all
                   ; back together.
                   p = StrSplit(parts[1], '[DdEe]', /RegEx, /Extract)

                   ; Round to the number of decimals you want.
                   fracpart = StrTrim(Round(Double('1.' + p[0]) * (10LL^decimals), /L64), 2)
                   IF StrMid(fracpart,0,1) EQ '2' THEN BEGIN
                     parts[0] = StrTrim(Long64(parts[0]) + 1, 2)
                   ENDIF
                   p[0] = StrMid(fracpart, 1)

                   ; Get the exponent sign and exponent part.
                   expSign = StrMid(p[1],0,1)
                   expPart = StrMid(p[1],1)

                   ; Trim zeros in exponent.
                   firstChar = StrMid(expPart, 0, 1)
                   WHILE firstChar EQ '0' DO BEGIN
                     expPart = StrMid(expPart, 1)
                     firstChar = StrMid(expPart, 0, 1)
                   ENDWHILE

                   ; Put it all back together.
                   retValue[j] = StrTrim(parts[0],2) + '.' + p[0] + StrLowCase(StrMid(parts[1],loc,1)) + expSign + expPart
                   END

            ENDCASE

            ; If you changed the number of decimals you were using, put it back.
            IF N_Elements(savedecimals) NE 0 THEN decimals = savedecimals
            END

         'DOUBLE': BEGIN
            ; Format the number with G format.
            aString = StrTrim(String(theNumber, Format='(G)'), 2)

            ; Split the number into a whole part and a fractional part.
            parts = StrSplit(aString, '.', /Extract)
            IF N_Elements(parts) EQ 1 THEN parts = [parts, '0']
            parts[1] = StrTrim(parts[1],2)

            ; Does the fractional part have an E or a D in it?
            loc = StRegEx(parts[1], '[DE]')
            CASE loc OF

               -1: BEGIN ; No exponent.

                   ; Round to the number of decimals you want.
                   fracpart = StrTrim(Round(Double('1.' + parts[1]) * (10LL^decimals), /L64), 2)
                   IF StrMid(fracpart,0,1) EQ '2' THEN BEGIN
                     parts[0] = StrTrim(Long64(parts[0]) + 1, 2)
                   ENDIF
                   parts[1] = StrMid(fracpart, 1)
                   retValue[j] = StrTrim(parts[0],2) + '.' + parts[1]
                   END

               ELSE: BEGIN

                   ; Divide the fractional part of the number up into parts.
                   ; Treat p[0] as you treated parts[1] above. Then put it all
                   ; back together.
                   p = StrSplit(parts[1], '[DdEe]', /RegEx, /Extract)

                   ; Round to the number of decimals you want.
                   fracpart = StrTrim(Round(Double('1.' + p[0]) * (10LL^decimals), /L64), 2)
                   IF StrMid(fracpart,0,1) EQ '2' THEN BEGIN
                     parts[0] = StrTrim(Long64(parts[0]) + 1, 2)
                   ENDIF
                   p[0] = StrMid(fracpart, 1)

                   ; Get the exponent sign and exponent part.
                   expSign = StrMid(p[1],0,1)
                   expPart = StrMid(p[1],1)

                   ; Trim zeros in exponent.
                   firstChar = StrMid(expPart, 0, 1)
                   WHILE firstChar EQ '0' DO BEGIN
                     expPart = StrMid(expPart, 1)
                     firstChar = StrMid(expPart, 0, 1)
                   ENDWHILE

                   ; Put it all back together.
                   retValue[j] = StrTrim(parts[0],2) + '.' + p[0] + StrLowCase(StrMid(parts[1],loc,1)) + expSign + expPart
                   END

            ENDCASE

            END

         'UINT': retValue[j] = StrTrim(String(theNumber),2)

         'ULONG': retValue[j] = StrTrim(String(theNumber),2)

         'LONG64': retValue[j] = StrTrim(String(theNumber),2)

         'ULONG64': retValue[j] = StrTrim(String(theNumber),2)

         ELSE: Message, 'Cannot format a number of this type: ' + Size(theNumber, /TNAME) + '.'

      ENDCASE

      ; Need a minus sign?
      IF minus THEN retValue[j] = '-' + retValue[j]

   ENDFOR

   IF N_Elements(retValue) EQ 1 THEN RETURN, retValue[0] ELSE RETURN, retValue

END ;----------------------------------------------------------------------------------------