str2double function for HEX values

I'm using str2doule to converter a cell with mixed value types. the input may be 0.123 or 0x1a, 0x1A, 0xAB, 0X1a, 0x1A, 0xAB.
I found str2double("0x1a") can return the right result 26, but str2double("0x1e") will return NaN.
The test is under version '9.11.0.2911900 (R2021b) Update 8'.
Is any other suggested way to converter values like this.
Thanks.

4 comentarios

Stephen23
Stephen23 el 27 de Jul. de 2026 a las 10:08
Editada: Stephen23 el 28 de Jul. de 2026 a las 2:55
"I found str2double("0x1a") can return the right result 26, but str2double("0x1e") will return NaN."
Apparently because the exponent gets detected before the base. See also:
Paul
Paul el 27 de Jul. de 2026 a las 21:35
Editada: Paul el 28 de Jul. de 2026 a las 0:03
The underlying issue is with sscanf with %f FormatSpec as called from str2double.
With %f, the sscanf doc page says that numeric field type is a "floating point number."
The str2double doc says "Text that represents a number can contain digits, a comma (thousands separator), a decimal point, a leading + or - sign, an e preceding a power of 10 scale factor ..."
Based on the doc pages should we expect str2double to correctly process hex strings? I'm not sure (even though it does for any input that does not end in "e")?
Also, the doc recommendation to replace str2double() with double(string()) dosn't work with hex strings
str2double({'0x1'})
ans = 1
double(string({'0x1'}))
ans = NaN
he
he el 28 de Jul. de 2026 a las 6:06
Thank you for your so detailed description, now I get the reason.
Paul
Paul el 28 de Jul. de 2026 a las 11:57
As previously suggested by @Stephen23 consider contacting tech support about your finding. It would seem that str2double should be consistent for all hex string inputs.

Iniciar sesión para comentar.

Respuestas (1)

Stephen23
Stephen23 el 27 de Jul. de 2026 a las 10:04
C = {'0.123', '0x1a', '0x1A', '0xAB', '0X1a', '0x1e', '12.5'};
V = cellfun(@convertValue, C)
V = 1×7
0.1230 26.0000 26.0000 171.0000 26.0000 30.0000 12.5000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
function val = convertValue(txt)
val = str2double(txt);
if isnan(val)
val = hex2dec(txt);
end
end

Categorías

Más información sobre Characters and Strings en Centro de ayuda y File Exchange.

Preguntada:

he
el 27 de Jul. de 2026 a las 9:09

Comentada:

el 28 de Jul. de 2026 a las 11:57

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by