Main Content

Format Numbers

By default, the DOM API uses the maximum number of digits needed to accurately represent a number as text in a report. To control the number of digits used to represent a number, specify a number format using these approaches:

Set Default Number Format

To set the default format specification that the DOM API uses to format numeric data, use the mlreportgen.dom.setDefaultNumberFormat function. Provide a format specification that is valid for sprintf and that uses the %f, %e, %E, %g, or %G operator. For example, this code specifies four digits after the decimal point:

mlreportgen.dom.setDefaultNumberFormat("%0.4f");
The default format applies for the duration of the MATLAB® session and applies to numbers in document elements, such as paragraphs, tables, and lists, and to numbers represented as mlreportgen.dom.Number objects. For example, this code uses the default format to represent pi in a report:
import mlreportgen.dom.*
setDefaultNumberFormat("%0.4f");
d = Document("myDoc","pdf");
append(d,Paragraph(pi));
close(d);
rptview(d);

In the report, pi is generated as 3.1416.

Specify Format for One Number

To specify the format for one number:

For example, this code uses the default number format for the first instance of pi and overrides the default format for the second instance of pi:

import mlreportgen.dom.*
setDefaultNumberFormat("%0.4f");
d = Document("myDoc1","pdf");

p1 = Paragraph("pi with default format: ");
append(p1,pi);
append(d,p1);

p2 = Paragraph("pi with number format: ");
n = Number(pi);
n.Style = {NumberFormat("%0.2f")};
append(p2,n);
append(d,p2);

close(d);
rptview(d);

Here are the numbers in the report:

First sentence is pi with default format 3.1416. Second sentence is pi with number format 3.14

Specify Number Format for Paragraphs, Tables, or Lists

You can specify the number format for all the numbers in a document element, such as a paragraph, table, or list by including an mlreportgen.dom.NumberFormat object in the Style property of the object that represents the document element. For example, this code specifies that the numbers in the first paragraph use the default format and that the numbers in the second paragraph have two digits after the decimal point:

import mlreportgen.dom.*
setDefaultNumberFormat("%0.4f");
d = Document("myDoc2","pdf");

p1 = Paragraph("pi with default format: ");
append(p1,pi);
append(d,p1);

p2 = Paragraph("pi with paragraph format: ");
p2.Style = {NumberFormat("%0.2f")};
append(p2,pi);
append(d,p2);

close(d);
rptview(d);

Here are the numbers in the report:

First paragraph is pi with default format 3.1416. Second sentence is pi with paragraph format 3.14.

For an example that specifies the format for all numbers in a table, see Format Numbers in Tables.

See Also

| | | |

Related Topics