# How can decimals not be rounded

1 view (last 30 days)
Shuoze Xu on 16 Jun 2022
Edited: the cyclist on 16 Jun 2022
Hi.
That is my code.
float_number = input('Please enter a float point number: ');
fprintf("The number is %.2f\n",float_number);
Sample test:
Please enter a float point number: 5.126
The number is 5.13
When the user enters a decimal, the result only keeps two decimal places, but I don't want the last decimal place to be rounded.
I don't want 5.13. I want 5.12.
How to do it?
Thank you.
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Accepted Answer

the cyclist on 16 Jun 2022
Edited: the cyclist on 16 Jun 2022
Here is one way:
roundTo = 2; % Set this value
float_number = 5.126; % User's value
% Algorithm
roundToPower = 10^roundTo;
roundedDisp = floor(float_number*roundToPower)/roundToPower;
fprintf("The number is %.2f\n",roundedDisp);
The number is 5.12
##### 3 CommentsShowHide 2 older comments
Walter Roberson on 16 Jun 2022
MATLAB does not provide any built-in function for this purpose.
For MacOS only (not sure if Linux was fixed yet), you can sprintf the number with a %.800g format, and do text manipulation on the result to get the number of decimal places you want.

Sign in to comment.

R2021b

### Community Treasure Hunt

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

Start Hunting!

Translated by