Literally convert decimal to string
古いコメントを表示
Hey!
I hope I have a simple question, I just couldn't figure it out.
I have several numbers which I want to be converted to string quite literally:
12.000 -> '12.000'
4.0 -> '4.0'
34.760000 -> '34.760000'
As you can see, I cannot simply pad zeros, since that highly depends on how many zero are given with the number.
Does anyone know how to do this?
8 件のコメント
"how many zero are given with the number" What does that mean?
sprintf( '%6.3f', 12 )
Ganesh Gebhard
2021 年 4 月 24 日
編集済み: Ganesh Gebhard
2021 年 4 月 24 日
per isakson
2021 年 4 月 24 日
編集済み: per isakson
2021 年 4 月 24 日
Sorry, I don't understand how to know whether there should be two or five zeros after the decimal point in a number.
Clayton Gotberg
2021 年 4 月 24 日
Where are you getting these numbers from? If they come from MATLAB I don't think it's possible to do that as it sees no difference between 12.000 and 12. However, MATLAB shouldn't be giving you numbers with inconsistent precision.
Stephen23
2021 年 4 月 24 日
"...since that highly depends on how many zero are given with the number."
Numeric data types do not explicitly store the number of decimal trailing zeros, so your examples do not correspond to the reality of how computers store numeric values.
"Does anyone know how to do this?"
You could store the required precision separately, and then use that information when converting to string.
dpb
2021 年 4 月 24 日
I would presume from "sometimes there are 5 zeros behind the comma and sometimes only two" that the source of the numbers must be a text file containing these. If that is the case, read them as text instead of as numeric to retain the wanted form, then as Stephen C suggests above parse the string to determine and store the desired precision if it is necessry to be able to reproduce this later. A stuct array might be a way to store such as a composite object.
Examples of the way these are generated and to be used might lead to more elegant solutions.
Ganesh Gebhard
2021 年 4 月 26 日
Scott MacKenzie
2021 年 4 月 26 日
編集済み: Scott MacKenzie
2021 年 4 月 26 日
Is the idea to replicate MATLAB's format for numbers appearing the command window? In this case, here's an idea that might help (but requires R2021a). Use fmt = format to get the current display format. fmt is a DisplayFormatOptions object. Query the DisplayFormatOptions object and respond accordingly:
format short
x = 5/4
fmt = format;
fmt.NumericFormat
% "short", therefore 4 digits after decimal point
format long
x
fmt = format;
fmt.NumericFormat
% "long", therefore 15 digits after decimal point
Output:
x =
1.2500
ans =
"short"
x =
1.250000000000000
ans =
"long"
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Characters and Strings についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!