GForth:将浮点数转换为字符串

GForth: Convert floating point number to String

原来很复杂的一个简单问题:

如何在 GForth 中将浮点数转换为字符串?所需的行为看起来像这样:

1.2345e fToString \ takes 1.2345e from the float stack and pushes (addr n) onto the data stack

我找不到这个词的确切词,所以我查看了 Gforth 来源。

显然,您可以使用 represent 字将最重要的数字打印到提供的缓冲区中,但这并不是最终输出。 represent returns 有效性和符号标志,以及小数点的位置。该词然后用于浮点打印词的所有变体(f.fp. fe.)。

可能最简单的方法是用你的词替换 emitemit 是一个延迟词),在你需要的地方保存数据,使用可用的浮动 pint打印单词,然后将 emit 恢复为原始值。

我也想听听首选的解决方案...

经过大量挖掘,我的一位同事发现了它:

f>str-rdp ( rf +nr +nd +np -- c-addr nr )

https://www.complang.tuwien.ac.at/forth/gforth/Docs-html-history/0.6.2/Formatted-numeric-output.html

Convert rf into a string at c-addr nr. The conversion rules and the meanings of nr +nd np are the same as for f.rdp.

并且来自 f.rdp

f.rdp ( rf +nr +nd +np – )

https://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Simple-numeric-output.html

Print float rf formatted. The total width of the output is nr. For fixed-point notation, the number of digits after the decimal point is +nd and the minimum number of significant digits is np. Set-precision has no effect on f.rdp. Fixed-point notation is used if the number of siginicant digits would be at least np and if the number of digits before the decimal point would fit. If fixed-point notation is not used, exponential notation is used, and if that does not fit, asterisks are printed. We recommend using nr>=7 to avoid the risk of numbers not fitting at all. We recommend nr>=np+5 to avoid cases where f.rdp switches to exponential notation because fixed-point notation would have too few significant digits, yet exponential notation offers fewer significant digits. We recommend nr>=nd+2, if you want to have fixed-point notation for some numbers. We recommend np>nr, if you want to have exponential notation for all numbers.

在人类可读的术语中,这些函数需要浮点堆栈上的数字和数据堆栈上的三个数字。

第一个数字参数告诉它字符串应该有多长,第二个参数你想要多少小数以及第三个告诉它 最小小数位数 (大致转化为精度)。执行大量隐式数学以确定生成的最终字符串格式,因此几乎需要进行一些修改才能使其按照您想要的方式运行。

正在对其进行测试(我们不想重建 f.,而是要生成一种可以被接受为浮点数的格式,然后再将其传递给 EVALUATE,所以 1.2345E0 符号是故意的):

PI 18 17 17 f>str-rdp type \ 3.14159265358979E0 ok
PI 18 17 17 f.rdp          \ 3.14159265358979E0 ok
PI f.                      \ 3.14159265358979  ok