필터 지우기
필터 지우기

How to cut digits after the decimal point?

조회 수: 137 (최근 30일)
Mark Golberg
Mark Golberg 2017년 3월 1일
댓글: Dyuman Joshi 2024년 1월 28일
Hello, I have the following variable:
a1 = 0.1234
I want to cut all digits after the first one after the decimal point. Meaning:
a2 = 0.1
I've created the following code (q=1 in our example):
b1 = a1 .* 10^q;
b2 = floor(b1);
a2 = b2 ./ (10^q);
But, it output
a2 = 0.1000
How can I get rid of the zeros in the end?
Thank you.

채택된 답변

John D'Errico
John D'Errico 2017년 3월 1일
편집: John D'Errico 2017년 3월 1일
You can use
a2 = round(a1,1);
to round to that decimal point.
However, to display the number with no zeros, you may want to change your display format.
format short
a2
a2 =
0.1000
format short g
a2
a2 =
0.1
See the difference between short, and short g.
I tend to leave the display format as short g always, except for the rare time when I want to see more digits, then I move to long g.
  댓글 수: 4
ΦΨ
ΦΨ 2024년 1월 28일
편집: ΦΨ 2024년 1월 28일
Is there an option to cut not round? Meaning:
1.59 -> 1.5
Dyuman Joshi
Dyuman Joshi 2024년 1월 28일
format shortg
%input
in = 1.59;
%digits to cut
n = 1;
%output
out = floor(in*10^n)/10^n
out =
1.5

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Adam
Adam 2017년 3월 1일
편집: Adam 2017년 3월 1일
a2 = round( a1, 1 );
if you have a sufficiently recent version of Matlab. I can't remember when this functionality was added to the round function though.

카테고리

Help CenterFile Exchange에서 Graph and Network Algorithms에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by