# Converting Decimal Numbers To Hexadecimal In Power Query M

This is a very short post! A lot of people have blogged about how to convert numbers between different bases in M (see for example Maxim Zelensky’s very elegant solution for converting from binary to decimal), but today I noticed there was a very easy way to convert a decimal number to hexadecimal using the Number.ToText() function: you just need to use “x” in the second parameter. For example:

Number.ToText(12, "x") //returns c
Number.ToText(123, "x") //returns 7b

I’m sure this will come in handy somewhere…

### 7 responses

1. This is excellent, Chris!

What’s your preferred approach for converting hexadecimal numbers into decimal? The shortest approach I’ve found so far was by Igor Cotruta:

Expression.Evaluate ( “0x” & HexString )

In your opinion, is Expression.Evaluate always safe to use?

• Curt Hagenlocher says:

The Power BI service still relies on static analysis for data source discovery, so doing data access via Expression.Evaluate can be problematic in that context. There’s no other specific concern I can think of; the use of #shared is probably a bigger “future risk” than Expression.Evaluate (though of course the two are often used together).

2. Thanks, Chris! I knew that I archived this post with good reason. Do you know to similarly convert a decimal number to binary?

• Sam Kanga says:

Hi Chris

I’ve been meaning to reply to this. This is the one I that wrote up with for my work scenario, it’s a lot simpler than the one in your link. I can’t remember where I got the recursive algorithm from, it was something that I found on Google.

1. Create a blank query, name it “number_tobinarytext”, and paste in this function below.

(
number_parameter as number,
optional text_from_parameter as nullable text
)

=>

let
text_from = if text_from_parameter = null then “” else text_from_parameter,
number_tobinarytext_function = if number_parameter <= 1 then Text.From(number_parameter) & text_from else @number_tobinarytext( Number.RoundDown( number_parameter / 2 ), Text.From( Number.Mod( number_parameter, 2 ) ) & text_from )

in

number_tobinarytext_function

This site uses Akismet to reduce spam. Learn how your comment data is processed.