Home >Backend Development >Golang >How to Convert a Long Hexadecimal String to a Truncated Decimal in Go?

How to Convert a Long Hexadecimal String to a Truncated Decimal in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 22:10:121067browse

How to Convert a Long Hexadecimal String to a Truncated Decimal in Go?

Hexadecimal String to Truncated Decimal

Converting a long hexadecimal string into decimal notation can be a challenge, especially when the resulting number exceeds the range of int64. To address this issue, Golang provides the math/big package.

Example Conversion

Consider the following hexadecimal string:

"0x00000000000000000000000000000000000000000000d3c21bcecceda1000000"

Using math/big

To convert this string using math/big, follow these steps:

import "math/big"

s := "0x00000000000000000000000000000000000000000000d3c21bcecceda1000000"
i := new(big.Int)
i.SetString(s, 16)

// Convert result to decimal (using %f formatting)
fmt.Printf("%f", i)

Truncating Decimal Places

To truncate the decimal to 18 decimal places, use the following format string:

%018.18f

Example Output

The output of the above code, formatted with 18 decimal places, is:

1000000000000000000.000000

Remember, the math/big package also supports TextMarshaler and fmt.Scanner interfaces for converting to and from strings.

The above is the detailed content of How to Convert a Long Hexadecimal String to a Truncated Decimal in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn