To read and parse a floating-point number from a bufio.Reader
in Go, you can use the following steps:
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
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)
ReadString
method:input, _ := reader.ReadString('\n')
strings.TrimSpace
method to remove leading and trailing whitespace from the input string:input = strings.TrimSpace(input)
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.
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.