Formatting number via java.text.DecimalFormat always returns error in SSJS

你。 提交于 2019-11-28 08:58:33

问题


I am trying to format a number using java.text.DecimalFormat in SSJS but it returns an error. Here is my code snippet.

var df:java.text.DecimalFormat = new java.text.DecimalFormat("000");
df.format(50);

This returns an error of Ambiguity when calling format(long) and format(double). So I tried to parse the number as double or long but still the same error.

df.format(java.lang.Long.parseLong("50"));     //Returns same error
df.format(java.lang.Double.parseDouble("50")); //Returns same error

I created a Java implementation of the above SSJS code and it works fine.

DecimalFormat df = new DecimalFormat("000"); 
return df.format(50);

I have quite a few lines of SSJS code (of which the above snippet is part of) and creating a new Java class for two lines seems too much effort. Anyone knows why this doesn't work in SSJS?


回答1:


@Naveen: Have you tried below code, it worked for me without creating any java class :)

var df:java.text.DecimalFormat = new java.text.DecimalFormat("000");
var dblNum: java.lang.Double = new java.lang.Double(50);
return df.format(dblNum);

Thanks, please let me know your comments on this ;)




回答2:


It does not work because SSJS cannot tell the difference between double and float (this is by design - javascript has only concept of number with 64 bit precision).

You can probably hack this with reflection:

var df:java.text.DecimalFormat = new java.text.DecimalFormat("000");
df.getClass().getMethod("format", Double.class).invoke(df, 50);

But I would rather create some custom java utils classes for this purpose. SSJS is awful for almost anything except for calling java.



来源:https://stackoverflow.com/questions/15087998/formatting-number-via-java-text-decimalformat-always-returns-error-in-ssjs

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