How to get the Nth digit after the decimal point of a floating-point number in Go

1 Answer

0 votes
package main

import (
	"errors"
	"fmt"
	"math"
	"strconv"
	"strings"
)

// GetNthDecimalDigit returns the Nth digit after the decimal point.
//
// Examples:
//   GetNthDecimalDigit(123.456789, 1) -> 4
//   GetNthDecimalDigit(123.456789, 2) -> 5
//   GetNthDecimalDigit(123.456789, 3) -> 6
//
// Parameters:
//   value    - Floating-point number to inspect.
//   position - Digit position after the decimal point (1-based).
//
// Returns:
//   The requested digit, or 0 if the digit does not exist.
func GetNthDecimalDigit(value float64, position int) (int, error) {
	if position < 1 {
		return 0, errors.New("position must be a positive integer")
	}

	// Work with positive values only.
	value = math.Abs(value)

	// Convert the number to a string with fixed precision.
	numberStr := strconv.FormatFloat(value, 'f', 15, 64)

	// Locate the decimal point.
	decimalPos := strings.Index(numberStr, ".")

	if decimalPos == -1 {
		return 0, nil
	}

	// Index of the requested digit.
	digitIndex := decimalPos + position

	if digitIndex >= len(numberStr) {
		return 0, nil
	}

	// Convert the character digit to an integer.
	return int(numberStr[digitIndex] - '0'), nil
}

func main() {
	number := 123.456789

	fmt.Printf("Number: %.6f\n\n", number)

	for i := 1; i <= 6; i++ {
		digit, err := GetNthDecimalDigit(number, i)
		if err != nil {
			fmt.Println("Error:", err)
			return
		}

		fmt.Printf("%d digit after decimal = %d\n", i, digit)
	}

	fmt.Println("\nAdditional Examples")
	fmt.Println("-------------------")

	digit, _ := GetNthDecimalDigit(123.456789, 4)
	fmt.Printf("123.456789, position 4 -> %d\n", digit)

	digit, _ = GetNthDecimalDigit(-98.7654, 2)
	fmt.Printf("-98.7654, position 2 -> %d\n", digit)

	digit, _ = GetNthDecimalDigit(1.2, 5)
	fmt.Printf("1.2, position 5 -> %d\n", digit)
}



/*
run:

Number: 123.456789

1 digit after decimal = 4
2 digit after decimal = 5
3 digit after decimal = 6
4 digit after decimal = 7
5 digit after decimal = 8
6 digit after decimal = 9

Additional Examples
-------------------
123.456789, position 4 -> 7
-98.7654, position 2 -> 6
1.2, position 5 -> 0

*/

 



answered Oct 15 by avibootz

Related questions

...