Fail to convert string to a number

조회 수: 1 (최근 30일)
Mallory Morton
Mallory Morton 2019년 12월 20일
댓글: Adam Danz 2019년 12월 20일
I've read in a Word Document and split the text based on certain delimiters. One of the strings i'm simply trying to convert to a number is " 329.3 " observing what appears to be a space character at the beginning and end of the string.
When I use str2double it converts it to "NaN". Normally leading and trailing whitespaces allow for conversion to a double with no problem.
If I run the isspace command it returns "1 0 0 0 0 0 0" so the last character is my issue, it isn't showing up as a whitespace character.
The strtrim command returns the string "329.3 " with only the leading whitespace removed. Strrep with attempting to replace the space returns the same result.
When I run the isstrprop command for each character Category the only one that returns true is the "print" category, "wspace" does not return true but for hte first character. Any ideas as to why the last character would not be showing up as a white space, isn't removeable, and prevents conversion from a string to a double?
  댓글 수: 1
Adam Danz
Adam Danz 2019년 12월 20일
Very well explained! +1

댓글을 달려면 로그인하십시오.

채택된 답변

Fangjun Jiang
Fangjun Jiang 2019년 12월 20일
편집: Fangjun Jiang 2019년 12월 20일
use double() to see the ASCII value
a=[char(32),'3.93',char(10)];
double(a)
  댓글 수: 2
Mallory Morton
Mallory Morton 2019년 12월 20일
It shows it is char 160 which is a non-breaking space character. Is there a way to manage those characters with MATLAB so that I can convert the string to a number? (strtrim doesn't remove significant whitespace characters)
Fangjun Jiang
Fangjun Jiang 2019년 12월 20일
strrep(YourStr,char(160),'')

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Adam Danz
Adam Danz 2019년 12월 20일
For those who are trying to recreate the problem,
t = [' 3.93',char(160)];
One solution is to use a regular expression to extract the numeric content.
n = regexp(t,'\d*\.?\d*','match')

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by