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
Release: 2024-12-10 22:10:12
Original
1005 people have browsed it

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"
Copy after login

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)
Copy after login

Truncating Decimal Places

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

%018.18f
Copy after login

Example Output

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

1000000000000000000.000000
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template