|
| 1 | +--- |
| 2 | +title: str2num |
| 3 | +--- |
| 4 | + |
| 5 | +# The `stdlib_str2num` module |
| 6 | + |
| 7 | +This module proposes a function-style interface for string-to-number conversion. It also profits from Fortran's interfaces to implement precision-dependant algorithms to maximize runtime efficiency. |
| 8 | + |
| 9 | +[TOC] |
| 10 | + |
| 11 | +## `to_num` - conversion of strings to numbers |
| 12 | + |
| 13 | +### Status |
| 14 | + |
| 15 | +Experimental |
| 16 | + |
| 17 | +### Description |
| 18 | + |
| 19 | +Convert a string or an array of strings to numerical types. |
| 20 | + |
| 21 | +### Syntax |
| 22 | + |
| 23 | +`number = [[stdlib_str2num(module):to_num(interface)]](string, mold)` |
| 24 | + |
| 25 | +### Arguments |
| 26 | + |
| 27 | +`string`: argument has `intent(in)` and is of type `character(*)`. |
| 28 | + |
| 29 | +`mold`: argument has `intent(in)` and is of numerical type (that is of `integer` or of `real`). **Note**: The type of the `mold` argument defines the type of the result. |
| 30 | + |
| 31 | +### Return value |
| 32 | + |
| 33 | +Return a scalar of numerical type (i.e., `integer`, or `real`). |
| 34 | + |
| 35 | +### Example |
| 36 | + |
| 37 | +```fortran |
| 38 | +{!example/strings/example_string_to_number.f90!} |
| 39 | +``` |
| 40 | + |
| 41 | +## `to_num_from_stream` - conversion of a stream of values in a string to numbers |
| 42 | + |
| 43 | +### Status |
| 44 | + |
| 45 | +Experimental |
| 46 | + |
| 47 | +### Description |
| 48 | + |
| 49 | +Convert a stream of values in a string to an array of values. |
| 50 | + |
| 51 | +### Syntax |
| 52 | + |
| 53 | +`number = [[stdlib_str2num(module):to_num_from_stream(interface)]](string, mold)` |
| 54 | + |
| 55 | +### Arguments |
| 56 | + |
| 57 | +`string`: argument has `intent(in)` and is of type `character(:), pointer`. |
| 58 | + |
| 59 | +`mold`: argument has `intent(in)` and is of numerical type (currently of `integer` or `real`). **Note**: The type of the `mold` argument defines the type of the result. |
| 60 | + |
| 61 | +### Return value |
| 62 | + |
| 63 | +Return a scalar of numerical type (i.e., `integer` or `real`). |
| 64 | + |
| 65 | +### Example |
| 66 | + |
| 67 | +```fortran |
| 68 | +{!example/strings/example_stream_of_strings_to_numbers.f90!} |
| 69 | +``` |
| 70 | + |
| 71 | +## Note |
| 72 | +The accuracy of the conversion is implementation dependent; it is recommended that implementers guarantee precision down to the last 3 bits. |
| 73 | + |
| 74 | +**The current implementation has been tested to provide for** : |
| 75 | + |
| 76 | +`sp` : exact match |
| 77 | + |
| 78 | +`dp` : precision up-to epsilon(0.0_dp) |
| 79 | + |
| 80 | +`qp` : precision around 200*epsilon(0.0_qp) |
| 81 | + |
| 82 | +Where precision refers to the relative difference between `to_num` and `read`. On the other hand, `to_num` provides speed-ups ranging from 4x to >10x compared to the intrinsic `read`. |
0 commit comments