Hey Ozcan,
I believe what you want to do can be achieved using regular expressions to parse the string and then convert the extracted value to the desired format. I have provided a code snippet that can help:
% JSON string
jsonString = '"text" : "18.0 km"';
% Extract the numeric value using regular expressions
tokens = regexp(jsonString, '"text" : "([\d\.]+) km"', 'tokens');
% Check if extraction was successful
if ~isempty(tokens)
% Convert the extracted string to a number
numValue = str2double(tokens{1}{1});
% Format the number to two decimal places
formattedValue = sprintf('%.2f', numValue);
% Display the result
disp(['Formatted Value: ', formattedValue]);
else
disp('No numeric value found in the JSON string.');
end
The “regexp()” function is used to extract the numeric value from the JSON string. The pattern '"text" : "([\d\.]+) km"' looks for a sequence of digits and periods ([\d\.]+) within the JSON format.
The tokens variable contains the extracted numeric string. It's nested in a cell array, so access it with tokens{1}{1}.
The “str2double()” function converts the extracted string to a numeric value. The sprintf('%.2f', numValue) function formats the numeric value to two decimal places.
This approach should work efficiently without needing external JSON parsing libraries, which might encounter compatibility issues.
The above code is for your particular use case, you can modify the regexp() expression based on the strings requirement and format
Here is the documentation of “regexp()” in case you need further information:
I hope that helps!