フィルターのクリア

How to change a numeral of a number?

1 回表示 (過去 30 日間)
Weyller Melo
Weyller Melo 2018 年 4 月 24 日
編集済み: James Tursa 2018 年 4 月 24 日
Hello friends, I want to change the LAST numeral of a number, i.e., I have 543.32145, and I want 543.32140. In fact, I have an array with 200 numbers, but these numbers have the same format than 543.32145, and I want all of them with a zero at the end.
Thank you all =)
  1 件のコメント
Stephen23
Stephen23 2018 年 4 月 24 日
@Weyller Melo: are these stored as text (e.g char), or numeric (e.g. double)?

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

回答 (1 件)

Stephen23
Stephen23 2018 年 4 月 24 日
編集済み: Stephen23 2018 年 4 月 24 日
If you have char vector/array:
>> str = '543.32145';
>> str(end) = '0'
str = 543.32140
If you have numeric values:
>> val = 543.32145
val = 543.32145
>> floor(val*1e4)/1e4
ans = 543.3214
  3 件のコメント
Stephen23
Stephen23 2018 年 4 月 24 日
編集済み: Stephen23 2018 年 4 月 24 日

"I have numeric values, but I'd like to see the zero (543.32140). Is it possible?"

In general no, because numeric classes do not store any formatting information whatsoever, and most of the format options suppress trailing zeros. But you could write your own fprintf command to do that:

>> val = 543.32145;
>> fprintf('%.5f\n',val)
543.32145
>> fprintf('%.5f\n',floor(val*1e4)/1e4)
543.32140
James Tursa
James Tursa 2018 年 4 月 24 日
編集済み: James Tursa 2018 年 4 月 24 日

@Weyller: Keep in mind that, in general, decimal fractions like you are using cannot be represented exactly in IEEE double precision arithmetic. E.g.,

>> num2strexact(543.3214)
ans =
    '5.43321400000000039653968997299671173095703125e2'
>> num2strexact(543.32145)
ans =
    '5.433214500000000271029421128332614898681640625e2'

Those are the closest IEEE double precision numbers to the ones you are using. So be careful how you use these downstream, particularly if you are comparing them to other numbers (e.g., for equality).

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

カテゴリ

Help Center および File ExchangeNumeric Types についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by