Ayan profile pictureAyan
13 min read8 views

Power Query Formatter: 4 Free Ways to Clean Up M Code (Plus Date and Number Formats)

Power BI still has no format button for M. Here are four free ways to turn one-line Power Query code into clean, readable steps, plus copy-paste M for formatting dates and numbers as text.

Power Query Formatter: 4 Free Ways to Clean Up M Code (Plus Date and Number Formats) - Power BI theme tutorial featured image

A Power Query formatter takes messy M code, the kind that sits on one long line in the Advanced Editor, and rewrites it with clean line breaks and indentation so you can read, review and debug it. Power BI Desktop has no format button for M, so the fastest options are a free online formatter, Microsoft's Power Query extension for VS Code, or a Tabular Editor macro.

Searches for "power query formatter" went Breakout in Google Trends this month (October 2026), so plenty of people are hitting the same wall. This guide is for Power BI developers and analysts who paste, inherit or review M code and want it readable in under a minute. It also covers the other thing people mean when they type "power query format": turning dates and numbers into exactly the text you need.

Key takeaways

  • The Advanced Editor can show line numbers and word wrap, but it cannot auto-format M code.
  • For a quick one-off, paste your code into a Power Query formatter online and copy it back.
  • For private code and daily work, use the free Power Query / M Language extension in VS Code and press Shift+Alt+F.
  • For a whole model, a Tabular Editor macro formats every partition and shared expression.
  • Formatting only moves whitespace, so your query returns the same table and folds the same way.
  • Date.ToText, Number.ToText and Text.PadStart handle date and number formats inside Power Query.

In this guide

What is a Power Query formatter?

Every click you make in Power Query becomes a step of M code. The editor writes that code for you, one step per line, but steps with nested lists, records and each functions quickly turn into walls of text. Code copied from a forum, a colleague or an AI chat is often worse: a whole query squeezed onto one line.

A formatter reads that M code and prints it back with consistent rules: one step per line, long lists and records broken over several lines, nested functions indented and operators spaced out. It is the M version of DAX Formatter, the tool SQLBI built for DAX. The logic does not change. Only whitespace and line breaks move, so the query returns exactly the same table.

Why format your Power Query M code at all?

  • Debugging: a syntax error such as Token Comma expected points to a line and a column. On formatted code you find it in seconds.
  • Code reviews and Git: when each step sits on its own line, a diff shows the one step that changed instead of one giant modified line.
  • Handover: the next person can read the query top to bottom like a recipe, without scrolling sideways.
  • Learning: formatted code shows you how M is built, which makes writing your own steps much easier.

How to use a Power Query formatter online

The best-known web tool is powerqueryformatter.com, built by the Power Pivot Insights team in Germany and announced on Chris Webb's blog in 2020. It is free, needs no sign-in, and works the same way DAX Formatter does: paste, format, copy.

  1. In Power BI Desktop, click Transform data to open the Power Query Editor in Power BI. (Stuck? See our guide on 6 ways to open Power Query Editor.)
  2. Select the query in the Queries pane, then go to Home > Advanced Editor.
  3. Press Ctrl+A, then Ctrl+C to copy the full query, from let to the last line after in.
  4. Open the formatter site, paste the code into the input box and run the formatter.
  5. Copy the formatted result.
  6. Back in the Advanced Editor, press Ctrl+A, paste, and click Done.
  7. Check the Applied Steps list. It should show the same steps as before, and the preview should load without errors.

There are newer browser tools too, such as the M formatter on Nanokit. They all follow the same paste-and-copy flow, so pick one you trust and stick with it.

Is it safe to paste M code into an online formatter?

It depends on what is in the code. M usually contains server names, database names, file paths and SharePoint URLs, and sometimes an API key that someone hard-coded into a Web.Contents header. Your saved credentials are not in the M code (Power BI keeps them in data source settings), but the rest can still be sensitive.

Sources describe the main site differently: Wise Owl says it formats in your browser, while the Tabular Editor script sends code to the site's API over HTTPS. My rule: if the code belongs to a client or touches internal systems, either swap the server names for placeholders before pasting or use the offline VS Code route below.

Power Query formatter VSCode setup (free and offline)

Microsoft maintains an open-source Power Query / M Language extension for Visual Studio Code. It bundles Microsoft's own powerquery-formatter library and connects it to VS Code's standard Format Document command. Nothing leaves your machine, which makes this the best everyday choice.

  1. Install Visual Studio Code if you do not have it.
  2. Open Extensions (Ctrl+Shift+X), search for Power Query and install the extension published by Microsoft (ID PowerQuery.vscode-powerquery).
  3. Create a new file and save it with the .pq extension, or use Change Language Mode in the status bar and pick Power Query.
  4. Paste your M code from the Advanced Editor.
  5. Press Shift+Alt+F (Format Document), or right-click and choose Format Document.
  6. Copy the result back into the Advanced Editor and click Done.

The extension also gives you autocomplete for the standard M library, hover help, function hints with argument checks, and commands to escape or unescape M and JSON strings. That last one is handy when M code is stored inside a JSON file such as a dataflow's model.json.

Format on save

If you keep your queries as .pq files, let VS Code format them every time you save. Add this to your settings.json:

{
    "[powerquery]": {
        "editor.formatOnSave": true
    }
}

Format Power Query in Tabular Editor and PBIP projects

Copy and paste is fine for one query. With 40 queries in a model it gets old fast. Tabular Editor (version 2 is free, version 3 is paid) can run C# scripts against your model, and a community script shared by Kurt Buhler of Data Goblins and in the Tabular Editor docs formats M for you. It sends the M of the selected partition or shared expression to the Power Query Formatter API and writes the formatted result back.

  1. Open your model in Tabular Editor. A Power BI Project (PBIP) folder is the safest target.
  2. Paste the Format Power Query script into a new C# Script window.
  3. Save it as a macro named Format Power Query and tick the Partition and Shared Expression contexts.
  4. Select one or more partitions or shared expressions, right-click and choose Macros > Format Power Query.
  5. Save the model and reopen or refresh it in Power BI Desktop.

Two things to know. First, the script calls a web API, so the privacy rule from the online section applies here too. Second, Tabular Editor formats DAX natively, but M only through this script, and writing partition changes back into an open .pbix through external tools has been restricted in the past, so test on a copy or use PBIP.

PBIP, TMDL and Git: why formatting matters more now

When you save a report as a Power BI Project, each table's Power Query M code is stored as plain text in TMDL files, which teams commit to Git. Format your M once before the first commit. After that, every diff shows only real logic changes instead of whitespace noise, and reviewers can actually read the pull request.

Make the Advanced Editor in Power BI easier to read

At the time of writing (October 2026), the Advanced Editor in Power BI has no one-click format command. What it does have is a Display options menu at the top of the window with four settings worth turning on or off:

  • Display line numbers: essential, because syntax errors refer to line numbers.
  • Enable word wrap: stops long steps from running off the right edge.
  • Render whitespace: shows tabs and spaces, useful when indentation looks uneven.
  • Display mini map: a scroll preview for very long queries.

Microsoft is also rolling out a new Power Query experience in Power BI Desktop as a preview, and the Advanced Editor is available in both versions. The Query overview on Microsoft Learn explains what differs.

Five rules to format M code by hand

No tool handy? These rules give you 90% of a formatter's result:

  1. One step per line: StepName = expression, with the comma at the end.
  2. Readable step names without spaces: rename #"Filtered Rows" to FilteredRows in Applied Steps, and Power Query updates every reference for you.
  3. Break long lists: put each {"Column", type} pair of a type change on its own line.
  4. Indent nested code by four spaces, including each functions and records.
  5. Comment the why, not the what: use // above a step to explain a business rule.

Worked example: messy vs formatted Power Query M code

Here is a real-world style query that loads a sales CSV, sets types, removes bad rows and totals sales by region. This is how it often arrives in a chat or forum post:

let Source=Csv.Document(File.Contents("C:\Data\Sales.csv"),[Delimiter=",",Columns=3,Encoding=65001]),Promoted=Table.PromoteHeaders(Source,[PromoteAllScalars=true]),Typed=Table.TransformColumnTypes(Promoted,{{"OrderDate",type date},{"Amount",type number},{"Region",type text}}),Filtered=Table.SelectRows(Typed,each [Amount]>0 and [Region]<>null),Grouped=Table.Group(Filtered,{"Region"},{{"Total",each List.Sum([Amount]),type number}}) in Grouped

And here is the same query after formatting. It is roughly what a formatter gives you; tools differ a little in where they break lines:

let
    Source = Csv.Document(
        File.Contents("C:\Data\Sales.csv"),
        [Delimiter = ",", Columns = 3, Encoding = 65001]
    ),
    Promoted = Table.PromoteHeaders(Source, [PromoteAllScalars = true]),
    Typed = Table.TransformColumnTypes(
        Promoted,
        {
            {"OrderDate", type date},
            {"Amount", type number},
            {"Region", type text}
        }
    ),
    Filtered = Table.SelectRows(
        Typed,
        each [Amount] > 0 and [Region] <> null
    ),
    Grouped = Table.Group(
        Filtered,
        {"Region"},
        {{"Total", each List.Sum([Amount]), type number}}
    )
in
    Grouped

Same five steps, same result. But now you can see at a glance that the filter keeps positive amounts with a region, and that Grouped is the step the query returns. If you want to add a step, you know exactly where it goes: after Grouped, with a comma, and then change the name after in.

Which Power Query formatter should you use?

ToolCostWhere your code goesBest forWatch out for
powerqueryformatter.comFreeWeb browser / web APIQuick one-offs, forum codeDo not paste secrets or client server names
VS Code + Power Query / M LanguageFreeStays on your PCDaily work, private code, GitYou copy code in and out of Power BI
Tabular Editor macroTE2 free, TE3 paidLocal tool that calls the formatter APIWhole models, PBIP projectsOne-time script setup; test on a copy
pqtools (Python, unofficial)FreeStays on your PCScripts and build pipelinesNot from Microsoft; check it is maintained
By hand in the Advanced EditorFreePower BI DesktopShort queriesSlow and inconsistent across a team

My recommendation: install the VS Code extension once and use it for everything. It is free, offline and from Microsoft. Keep the online formatter for code that is already public, and add the Tabular Editor macro when you start working with PBIP projects and Git.

Power Query format: dates and numbers as text

Many people typing "power query format" do not want to format code at all. They want 2026-10-30 to show as 20261030, or store 42 to show as 00042. You do this in a custom column: Add Column > Custom Column, then paste one of the formulas below. Function details are in the Date.ToText and Number.ToText references on Microsoft Learn.

Power Query format date as text

Use Date.ToText with a Format and a Culture, so the month names do not change with the computer's language settings:

Date.ToText([OrderDate], [Format = "dd MMM yyyy", Culture = "en-US"])
// 30 Oct 2026

Watch the case: MM is month, mm is minutes. A format of "yyyy-mm-dd" gives you minutes where the month should be, and on a date value that means 00.

Power Query format date as yyyymmdd

For a text key, use the compact format. For a whole-number date key (common in fact tables), build the number with math, which is faster and needs no text conversion:

// as text: "20261030"
Date.ToText([OrderDate], [Format = "yyyyMMdd"])

// as a whole number: 20261030
Date.Year([OrderDate]) * 10000 + Date.Month([OrderDate]) * 100 + Date.Day([OrderDate])

Power Query format number 2 decimal places

First decide whether you need a number or text. To keep a number, round it, and pass a rounding mode, because Number.Round uses banker's rounding by default (1.125 becomes 1.12, not 1.13):

// number, rounded the way most people expect
Number.Round([Amount], 2, RoundingMode.AwayFromZero)

// text with thousands separator: "1,234.50"
Number.ToText([Amount], "N2", "en-US")

// text without separator: "1234.50"
Number.ToText([Amount], "F2", "en-US")

For values you will sum in visuals, keep them as numbers and set the display format in the model (Column tools > Format) instead. Text columns cannot be totalled.

Power Query format number with leading zeros

Product codes, store IDs and ZIP codes often need a fixed width. Text.PadStart is the clearest way:

// 42 becomes "00042"
Text.PadStart(Text.From([StoreID]), 5, "0")

// same result with a standard number format (whole numbers only)
Number.ToText([StoreID], "D5")

Power Query text format examples

To clean text in several columns at once, transform them in a single step instead of adding one custom column each:

Table.TransformColumns(
    Source,
    {
        {"Customer", Text.Proper, type text},
        {"CountryCode", Text.Upper, type text},
        {"Email", each Text.Lower(Text.Trim(_)), type text}
    }
)

Common problems and fixes

The formatter says the code is invalid

Formatters need the complete query, from let to the final step name after in. If you copied only part of it, or the query already has a syntax error, the parser stops. Fix the error in Power BI first (the Advanced Editor shows a message at the bottom), then format.

Expression.SyntaxError after pasting the code back

The usual causes are a comma after the last step before in, a missing comma between two steps, or curly quotes that sneaked in through Word, Teams or a chat app. Replace any “ and ” with straight double quotes and check the line number in the error.

Comments moved or disappeared

Some formatters move comments to a new line or drop comments in unusual places. Keep the original code in a text file until you have checked the result, and put comments on their own line above a step, where every tool keeps them.

Will formatting break query folding?

No. Query folding depends on the functions and their order, not on whitespace. If folding changed after a "format", something other than whitespace was edited, so compare the two versions line by line.

Date.ToText returns an error

If the column is text that only looks like a date, Date.ToText fails. Change the column type to Date first, or wrap it: Date.ToText(Date.From([OrderDate]), [Format = "yyyyMMdd"]).

Other Power BI formatter tools: DAX Formatter and format painter

DAX Formatter

DAX and M are different languages, so their formatters are not interchangeable. For DAX, use SQLBI's DAX Formatter website, the built-in DAX formatting in Tabular Editor, or the Format query button in Power BI Desktop's DAX query view. A Power Query formatter will reject DAX, and DAX Formatter will reject M.

Format painter for visuals

If you searched for a Power BI formatter because you want two visuals to look the same, you want the Format painter on the Home ribbon: select the styled visual, click Format painter, then click the visual you want to restyle. For colours and fonts across a whole report, a theme is better than painting visual by visual. Our free Power BI theme builder creates the theme JSON for you, and the Power BI templates come with clean layouts ready to fill.

Conclusion: pick one Power Query formatter and make it a habit

Readable M code is not a nice-to-have once a report grows past a few queries. A Power Query formatter takes seconds and saves you every time you debug, hand over or review a model. Start simple:

  • Today: install the Power Query / M Language extension in VS Code and format your longest query.
  • This week: turn on line numbers and word wrap in the Advanced Editor, and rename steps with spaces.
  • Next project: save it as PBIP, format all M with the Tabular Editor macro, then make your first Git commit.

Bookmark the date and number snippets above, too. They answer the other "power query format" question you will meet on almost every project.

FAQ

Is there a Power Query formatter built into Power BI Desktop?

Not at the time of writing (October 2026). The Advanced Editor offers line numbers, word wrap, whitespace and a mini map under Display options, but no format command, so use an online formatter, VS Code or Tabular Editor.

Is the Power Query formatter online free?

Yes, powerqueryformatter.com is free and needs no account, and it also offers an API. Remove server names, URLs and any keys before pasting code that belongs to a client.

How do I format M code in VS Code?

Install Microsoft's Power Query / M Language extension, open or save your code as a .pq file, and press Shift+Alt+F. The formatting runs locally, so your code never leaves your computer.

Does formatting change the result of my query?

No. A formatter only changes spaces, tabs and line breaks. The steps, their order and the output table stay the same, and query folding is not affected.

How do I format a date as text in Power Query?

Add a custom column with Date.ToText([YourDate], [Format = "dd/MM/yyyy", Culture = "en-US"]). Use capital MM for months, because lowercase mm means minutes.

How do I show a number with 2 decimal places in Power Query?

To keep it numeric, use Number.Round([Amount], 2, RoundingMode.AwayFromZero). To get text, use Number.ToText([Amount], "N2") for "1,234.50" or "F2" for "1234.50".

How do I add leading zeros in Power Query?

Use Text.PadStart(Text.From([ID]), 5, "0") to turn 42 into "00042". Change 5 to the total width you need; the result is a text column.

What is the difference between DAX Formatter and a Power Query formatter?

DAX Formatter formats DAX measures and queries, while a Power Query formatter formats M code from the Advanced Editor. They are separate languages with separate parsers, so each tool only accepts its own language.

Power BI TemplatesView all →

Latest Power BI Tutorials

Ready to create your Power BI theme?

Start designing professional themes in minutes

Launch Studio
Power Query Formatter: 4 Free Ways to Format M Code