How to convert a number to a string in Smalltalk (visual works)

自作多情 提交于 2019-12-13 16:26:27

问题


I am having difficulty finding information on how to get a string representation of a number in Cincom Smalltalk. How is this performed in this language? Specifically I'm composing a string representation of an object, similar to the toString function in Java.


回答1:


The printString method is meant to return a string to allow a programmer to interpret the number. If you used 3.14d in your example (a Double), you would see the 'd' character in the printString.

This is fine for developers but if you're building a user interface for other people to use, you should use a PrintConverter. Here's an example:

(PrintConverter for: #number withFormatString: '$#,###.##;[RED]($#,###.##);$0.00')
formatStringFor: -35675.389d

If you inspect the result, you'll see that it's red text in parentheses (because it's negative) and rounded to two decimal places with a leading dollar sign. This is a much better kind of number to display for a user interface. For information on the formatting characters, see the class comment for NumberPrintPolicy.




回答2:


After further research the needed message is printString. For example,

| str num |
num := 3.14.
str := 'An approximate value of pi is ', (num printString).



回答3:


To convert any Object into an user readable String use 'asString'.

| str num |
num := 3.14.
str := 'An approximate value of pi is ', num asString.

Many String methods convert their parameter value automagicaly into String, so you do not have to call/send/whatever it explicitly:

| str num |
num := 3.14.
str := 'An approximate value of pi is ', num .

(tested with ObjectStudio 8.3.1, a Windows smalltalk based on Visualworks; but the examples should work with any smalltalk available)




回答4:


Right way:

Locale current printAsNumber: 1

It uses the current locale settings in image.



来源:https://stackoverflow.com/questions/19104125/how-to-convert-a-number-to-a-string-in-smalltalk-visual-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!