gpt4 book ai didi

emacs - 如何转换为美元和美分——四舍五入,并使用逗号分隔符

转载 作者:行者123 更新时间:2023-12-01 08:59:40 25 4
gpt4 key购买 nike

以下代码摘录会将一列数字相加并产生几个小数点长的结果。任何人都可以举例说明如何将结果转换为美元和美分,四舍五入到第二位小数 - 即 1.555应该四舍五入到 1.56 ;和 1.554应该四舍五入到 1.55 .另外,我想在小数点左侧每三位数字插入逗号分隔符 - 例如,1124412.555应转换为 1,124,412.56 .

(let ((sum 0))
(while (re-search-forward "[0-9]*\\.?[0-9]+" nil t)
(setq sum (+ sum (string-to-number (match-string 0)))))
(insert "\n\nTotal Hours: " (format "%s" sum ))
(insert "\n\nTotal Fee for Services Rendered: " (format "%s" (* 250 sum)))
(insert "\n\nOne-third of total fee: " (format "%s" (/ (* 250 sum) 3))))

2.0
0.2
0.1
4.75
4.0
6.5
0.1

Total Hours: 17.650000000000002

Total Fee for Services Rendered: 4412.500000000001

One-third of total fee: 1470.8333333333337

根据@Drew 和@abo-abo 提供的答案,以下是现在似乎可以正常工作的修订草案:
08884.75585
78774.1235
6.545

Total Hours: 87,665.42

Total Fee: $21,916,356.09

One-Third: $7,305,452.03

(let ((sum 0))
(while (re-search-forward "[0-9]*\\.?[0-9]+" nil t)
(setq sum (+ sum (string-to-number (match-string 0)))))
(setq total-hours (group-number (number-conversion (format "%s" sum ))))
(setq services-rendered (group-number (number-conversion (format "%s" (* 250 sum)))))
(setq one-third (group-number (number-conversion (format "%s" (/ (* 250 sum) 3)))))
(insert "\n\nTotal Hours: " total-hours)
(insert "\n\nTotal Fee: $" services-rendered)
(insert "\n\nOne-Third: $" one-third) )

;; @abo-abo
(defun number-conversion (str)
(let ((x (read str)))
(format "%0.2f" (* 0.01 (round (* 100 x)))) ))

;; http://www.emacswiki.org/emacs/ElispCookbook#toc23
(defun group-number (num &optional size char)
"Format NUM as string grouped to SIZE with CHAR."
;; Based on code for `math-group-float' in calc-ext.el
(let* ((size (or size 3))
(char (or char ","))
(str (if (stringp num)
num
(number-to-string num)))
(pt (or (string-match "[^0-9a-zA-Z]" str) (length str))))
(while (> pt size)
(setq str (concat (substring str 0 (- pt size))
char
(substring str (- pt size)))
pt (- pt size)))
str))

最佳答案

我相信abo-abo的(* 0.01 (round (* 100 x)))在极端情况下可能会导致意外(因为 0.01 无法在内部浮点表示中准确表示)。一个更简单的四舍五入解决方案是:

(format "%0.2f" x)

关于emacs - 如何转换为美元和美分——四舍五入,并使用逗号分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20100944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com