Put the separator every thousands

13 ビュー (過去 30 日間)
Luca Re
Luca Re 2024 年 2 月 10 日
コメント済み: Image Analyst 2024 年 2 月 11 日
T=100000000;
T1 = regexprep(string(T),'(\d+)(\d{3})$',"$1'$2")
T1 = "100000'000"
I would like to have the thousands separator for every 1000
the correct result would be:
1'000'000'000
  2 件のコメント
Stephen23
Stephen23 2024 年 2 月 10 日
編集済み: Stephen23 2024 年 2 月 10 日
"the correct result would be: 1'000'000'000"
Why should the "correct result" be one billion when the input value is only one hundred million?
100000000 % your input value
1000000000 % your "correct result" with quotes removed
Your "correct result" is ten times larger than the input value: is that intentional or is it ... incorrect ?
Luca Re
Luca Re 2024 年 2 月 10 日
Yes, I counted the zeros wrong :DI to communicate 1000000000 become should 1'000'000'000

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2024 年 2 月 10 日
編集済み: Stephen23 2024 年 2 月 10 日
Here are some more interesting testcases (with both one hundred million as well as one billion):
S = ["100000000";"1000000000";"123456789.123456789";"-123456789";"0";pi;"1e23456"]
S = 7×1 string array
"100000000" "1000000000" "123456789.123456789" "-123456789" "0" "3.1416" "1e23456"
S = regexprep(S,"(?<![eE\.]\d*)\d{1,3}(?=(\d{3})+\>)","$&'")
S = 7×1 string array
"100'000'000" "1'000'000'000" "123'456'789.123456789" "-123'456'789" "0" "3.1416" "1e23456"
  1 件のコメント
Luca Re
Luca Re 2024 年 2 月 10 日
Good 👍👍

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2024 年 2 月 10 日
I use the attached function I wrote. Adapt as needed, like change commas to apostrophes if you want.
  2 件のコメント
Stephen23
Stephen23 2024 年 2 月 10 日
CommaFormat('-123456') % ouch
ans = '-,123,456'
Image Analyst
Image Analyst 2024 年 2 月 11 日
@Stephen23 thanks for pointing that out. I've corrected it to properly handle cases where the input is negative or a string or a character array instead of a number (double, etc.). New code is attached.
It's definitely more lines than your one liner regexp though. However I'm not as adept with regexp as you -- I never would have figured out that cryptic sequence of regexp characters as you did.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by