lisp 提取字符串中的數字,如何在Scheme Lisp中将字符串转换为精确数字?

For example, I have this string: "6119726089.12814713"

If I do (string->number "6119726089.12814713") - using the SISC implementation the result is 6.119726089128147e9 - and in Guile implementation is 6119726089.128147 but I would like an exact number, like: 611972608912814713/100000000 without loss precision.

I'd like a function like (string->exact) or something like this.

NOTE: please fix my non-native English and remove this message. Thanks.

解决方案

Use (string->number "#e6119726089.12814713") to parse the number as exact. This works for at least Racket and Guile. It may not work correctly on other Scheme implementations, however; they are at liberty to parse as inexact first, then convert.

Here's a portable implementation of the string->exact function that the OP asked for. I've manually tested it with a range of inputs, but you should do your own testing to ensure it fits your needs:

(define (string->exact str)

(define zero (char->integer #\0))

(let loop ((result #f)

(factor 1)

(seen-dot? #f)

(digits (string->list str)))

(if (null? digits)

(and result (/ result factor))

(let ((cur (car digits))

(next (cdr digits)))

(cond ((and (not result) (not seen-dot?) (char=? cur #\-))

(loop result (- factor) seen-dot? next))

((and (not seen-dot?) (char=? cur #\.))

(loop result factor #t next))

((char<=? #\0 cur #\9)

(loop (+ (* (or result 0) 10) (- (char->integer cur) zero))

(if seen-dot? (* factor 10) factor)

seen-dot? next))

(else #f))))))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值