且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Matlab:正则表达式将字符串中的长小数点转换为小数点后一定位数的小数点?

更新时间:2023-02-19 10:21:28

我建议对动态替换表达式使用regexprep:

I suggest using regexprep with dynamic replacement expression:

regexprep(inputString,'([0-9\.E-]+)','${sprintf(''%8.6f'',str2double($0))}')

这是第一个字符串的结果(注意:它是正确地"四舍五入,而不是四舍五入的数字)

Here's the result for the first string (note: it's rounding "correctly", rather than chopping off digits)

\left(\begin{array}{ccc} 0.000000 & 0.002325 & 0.002322 & 0.002324 \end{array}\right)

这是第二个更难输入的字符串的结果

Here is the result for the second, harder, input string

\left(\begin{array}{ccc} 0.000000 & 0.002324 & 0.002321 & 0.002323 \end{array}\right)

编辑

刚注意到它说更难的 output 字符串"-这是实现该目标的方法(尽管它确实总是带有两位数的指数).当然,如果您不想匹配指数符号,则可以在match表达式中省略E-.

Just noticed that it says "harder output string" - here's how to achieve that (though it does come with an always two-digit exponent). You can, of course, leave out the E- in the match expression if you don't want to match exponential notations.

out = regexprep(instr,'([0-9\.E-]+)','${sprintf(''%5.3e'',str2double($0))}')
ans =
\left(\begin{array}{ccc} 1.100e-12 & 2.325e-03 & 2.322e-03 & 2.324e-03 \end{array}\right)