lettura simple

How to change number format in Octave

Octave automatically displays the result of the operation in integer format if the result is integer or in decimal format if it is decimal.

Note. Unlike other programming languages, it does not consider the starting format of the operands.

For example, if you type 3.0+4.0 it returns 7 and not 7.0

>> 3.0+4.0
ans = 7

If instead you type 3.1+4 Octave it returns 7.1

>> 3.1+4.0
ans = 7.1

The long and short format

By default Octave displays the result output in short decimal format, i.e. with five significant digits.

>> 2/3
ans = 0.66667

However, you can change this setting.

To display the result with more significant digits, you need to set the long mode using the format long command

>> format long
>> 2/3
ans = 0.666666666666667

Long mode is not permanent. it remains active until the end of the work session.

You can switch back to short mode at any time by typing the format short command.

>> format short
>> 2/3
ans = 0.66667

Scientific notation

If you want to display the results using ten-base scientific notation, type format short e or format long e

>> format short e
>> 2/3
ans = 6.6667e-01

To return to normal mode type the command format short or format long.

Note. If you want to go back to the default format, you can also just type format command because the short option is the default setting.

Alternatively you can use the format short g and format long g commands which allow you to use scientific notation only if the situation requires it

In this case, Octave decides whether to use scientific notation or not.

>> format short g
>> 2/3
ans = 0.66667
>> 2*100000
ans = 2e+05

Another possibility provided by Octave are the format short eng or format long eng commands.

In this case the result is always in exponential format with the exponent divisible by three.

>> format short eng
>> 2/3
ans = 666.6667e-003
>> 2*100000
ans = 200.0000e+003

Other Octave number formats

Octave also allows you to set the rational approximation format via the format rat command

In this case the real numbers are approximated with a fraction or a sum of fractions.

For example, if you write 1.2 Octave it automatically turns it into the fraction 6/5

>> format rat
>> 1.2
ans = 6/5

Report a mistake or post a question