Convert from Character Arrays to Numeric Values

Function Summary

The functions listed in this table provide a number of ways to convert character arrays to numeric data.

Function

Description

Example

double, single

uint8, uint16, uint32, uint64

int8, int16, int32, int64

Convert a character to an integer code that represents that character.

'Hi'72 105

str2num

Convert a character type to a numeric type.

'72 105'[72 105]

str2double

Similar to str2num, but offers better performance and works with string arrays and cell arrays of character vectors.

"72" "105" [72 105]

{'72' '105'} [72 105]

hex2num

Convert a numeric type to a character type of specified precision, returning a character array that MATLAB® can evaluate.

'A''-1.4917e-154'

hex2dec

Convert a character type of hexadecimal base to a positive integer.

'A'10

bin2dec

Convert a character type of binary number to a decimal number.

'1010'10

base2dec

Convert a character type of any base number from 2 through 36 to a decimal number.

'12'10 (if base == 8)

Convert from Character Code

Character arrays and string arrays store each character as a 16-bit numeric value. Use one of the integer conversion functions (e.g., uint8) or the double function to convert characters to their numeric values, and char to revert to character representation:

name = 'Thomas R. Lee';

name = double(name)
name =
    84  104  111  109  97  115  32  82  46  32  76  101  101

name = char(name)
name =

    'Thomas R. Lee'

Convert Text that Represents Numeric Values

Use str2num to convert a character array to the numeric value it represents:

chr = '37.294e-1';

val = str2num(chr)
val =

    3.7294

The str2double function converts a string array or a cell array of character vectors to the double-precision values they represent:

c = {'37.294e-1'; '-58.375'; '13.796'};
str = string({'3.14159','2.718'});

d = str2double(c)

d =

    3.7294
  -58.3750
   13.7960

x = str2double(str)

x =

    3.1416    2.7180

whos
  Name      Size            Bytes  Class     Attributes

  c         3x1               380  cell                
  d         3x1                24  double              
  str       1x2               196  string              
  x         1x2                16  double              

Convert from Specific Radix

To convert from a character representation of a nondecimal number to the value of that number, use one of these functions: hex2num, hex2dec, bin2dec, or base2dec.

The hex2num and hex2dec functions both take hexadecimal (base 16) inputs, but hex2num returns the IEEE® double-precision floating-point number it represents, while hex2dec converts to a decimal integer.