How to read and parse a floating-point number from a bufio.Reader in Go?

To read and parse a floating-point number from a bufio.Reader in Go, you can use the following steps:

  1. Import the required packages:
import ( "bufio" "fmt" "os" "strconv" "strings" )
  1. Create a bufio.Reader to read input from the desired source (e.g., os.Stdin for reading from the command-line input):
reader := bufio.NewReader(os.Stdin)
  1. Read a line of input from the reader using the ReadString method:
input, _ := reader.ReadString('\n')
  1. Use the strings.TrimSpace method to remove leading and trailing whitespace from the input string:
input = strings.TrimSpace(input)
  1. Convert the input string to a float64 using the strconv.ParseFloat function:
number, err := strconv.ParseFloat(input, 64) if err != nil { fmt.Println("Invalid input:", err) return }

Here, 64 specifies the precision of the floating-point number. You can choose a different value based on your requirements.

  1. Use the parsed floating-point number as needed in your program:
fmt.Println("Parsed number:", number) // You can perform further calculations or operations using the parsed number

Overall, the complete code will look like this:

package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { reader := bufio.NewReader(os.Stdin) fmt.Print("Enter a floating-point number: ") input, _ := reader.ReadString('\n') input = strings.TrimSpace(input) number, err := strconv.ParseFloat(input, 64) if err != nil { fmt.Println("Invalid input:", err) return } fmt.Println("Parsed number:", number) // You can perform further calculations or operations using the parsed number }

When you run the program, it will prompt you to enter a floating-point number. Once you enter the number, it will parse and display the result.