How to format a DOUBLE to print only two decimals in Eiffel?

耗尽温柔 提交于 2019-12-11 02:39:52

问题


In eiffel how do you make it so that the number.

118.1999999999999

prints to:

118.20 

In other language is simply a matter of printf but there seems no to be a way to do that easily in Eiffel.


回答1:


You should use the class FORMAT_DOUBLE

local
    fd: FORMAT_DOUBLE
do
    create fd.make (5, 3)
    print (fd.formatted ({REAL_64} 12345.6789)) --> "12345.679"
    print (fd.formatted ({REAL_64} 12345.6)) --> "12345.600"
    print (fd.formatted ({REAL_64} 0.6)) --> "0.600"

    create fd.make (10, 2)
    fd.right_justify
    print (fd.formatted ({REAL_64} 1.678)) --> "      1.68"

    create fd.make (20, 3)
    fd.right_justify
    print ("[" + fd.formatted ({REAL_64} 12345.6789) + "]%N") --> [           12345.679]
    fd.left_justify
    print ("[" + fd.formatted ({REAL_64} 12345.6789) + "]%N") --> [12345.679           ]
    fd.center_justify
    print ("[" + fd.formatted ({REAL_64} 12345.6789) + "]%N") --> [      12345.679     ]

And so on ...

There is also a set of classes to mimic "printf" , you can find them at http://www.amalasoft.com/downloads.htm I haven't used them myself, but that might address your needs.

This is using ECMA Eiffel (I am not sure where comes from the previous response, but DOUBLE does not have such function `to_string_format'. And DOUBLE is the old name for REAL_64




回答2:


For example:


class DOBLE

creation
    make

feature
    make is
      local
          n: DOUBLE
          output: STRING
      do
          n := 118.1999999999999
          output := n.to_string_format(2) -- 2 digits in fractionnal part
          std_output.put_string(output + "%N")
      end
end


来源:https://stackoverflow.com/questions/3393178/how-to-format-a-double-to-print-only-two-decimals-in-eiffel

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