Number Parsing in Racket

#lang racket

(require racket/string)

(define (main)
  ; With string->number, we can parse floating-point numbers
  (define f (string->number "1.234"))
  (println f)

  ; For parsing integers, we can use string->number with an optional radix
  (define i (string->number "123"))
  (println i)

  ; string->number will recognize hex-formatted numbers when given a radix of 16
  (define d (string->number "1c8" 16))
  (println d)

  ; For parsing unsigned integers, we can use the same function
  (define u (string->number "789"))
  (println u)

  ; string->number is a general function for parsing numbers
  (define k (string->number "135"))
  (println k)

  ; string->number returns #f on bad input
  (define e (string->number "wat"))
  (println e))

(main)

Racket provides built-in functions for parsing numbers from strings. The string->number function is the primary tool for this task.

With string->number, we can parse both floating-point and integer numbers. The function takes an optional second argument to specify the radix for integer parsing.

For parsing floating-point numbers, we simply pass the string to string->number:

(define f (string->number "1.234"))
(println f)

For parsing integers, we can use string->number without specifying a radix, which defaults to 10:

(define i (string->number "123"))
(println i)

string->number will recognize hex-formatted numbers when given a radix of 16:

(define d (string->number "1c8" 16))
(println d)

For parsing unsigned integers, we can use the same function:

(define u (string->number "789"))
(println u)

string->number is a general function for parsing numbers:

(define k (string->number "135"))
(println k)

Unlike the Go version, which returns an error on bad input, string->number returns #f (false) when it can’t parse the input:

(define e (string->number "wat"))
(println e)

To run the program, save it as number-parsing.rkt and use the racket command:

$ racket number-parsing.rkt
1.234
123
456
789
135
#f

This example demonstrates how to parse various types of numbers from strings in Racket. The string->number function provides a unified interface for parsing both floating-point and integer numbers, with support for different bases.