简体   繁体   English

如何在MatLab中添加前导零(数字格式)?

[英]How to add leading zeros in MatLab (number formatting)?

Here is a very specific example 这是一个非常具体的例子

>> S = num2str(12345,'%6.0e')
S =
1e+04

and that's just great since I want only my first digit and an exponential notation. 这很好,因为我只需要我的第一个数字和一个指数表示法。 However I also want to add leading zeros to the exponent in order to fill the width, but I cannot quite find the way to get the following... 但是我也想为指数添加前导零以填充宽度,但我找不到获得以下内容的方法......

1e+004

Meanwhile it's very straighforward to pad the significant digits with leading zeros 同时用前导零填充有效数字是非常直接的

>> S = num2str(12345,'%06.0e')
S =
01e+04

So is there an appropriate formatting for what I want? 那么我想要的是适当的格式吗? Or a trick to accomplish it quickly? 或者快速完成它的技巧?

The exponent is always a zero-padded two-digit value. 指数始终是零填充的两位数值。 To add, say, two zeros you can use 例如,添加两个可以使用的零

regexprep(num2str(12345, '%6.0e'), '\+', '\+00')

and achieve 并实现

ans =
1e+0004

Edit: To cover negative exponents you may use 编辑:覆盖您可能使用的负指数

regexprep(num2str(0.12345, '%6.0e'), '(\+|\-)', '$100')

to achieve 实现

ans =
1e-0001

And, to cover three-digit exponents 并且,涵盖三位数的指数

regexprep(num2str(1e-100, '%6.0e'), '(\+|\-)(\d{2,3})$', {'$10$2', '$10$2'})

ans =
1e-0100

regexprep(num2str(1e-10, '%6.0e'), '(\+|\-)(\d{2,3})$', {'$10$2', '$10$2'})

ans =
1e-0010

Well, I think you have to edit, what you say you want is wat you get :D 好吧,我认为你必须编辑,你说你想要的是你得到的:D

however, if I understood correctly what you are looking for, this function will help you 但是,如果我理解你正在寻找什么,这个功能将帮助你

function printX(x, digits)
    format = sprintf('\t%%.%de', digits - 1);
    strcat(inputname(1), ' = ', sprintf(format, x))
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM