Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 600
  • Last Modified:

Num Format in the Java

Hi,

I have a code in javascript:

function num_format(x, presymbol, postsymbol)
{     // format numbers with two digits
     sgn = (x < 0);
     x = Math.abs(x);
     x = Math.floor((x * 100) + .5);
     i = 3;
     y = "";
     k = 0;
     while(((i--) > 0) || (x > 0)) {
          y = (x % 10) + y;
          x = Math.floor(x / 10);
          if(i == 1) {
               y = "." + y;
          }
          if (i<1) {
               k ++;
               if (k%3 == 0) {
                    if (x>0) {
                         y = "," + y;
                    }
               }
          }
     }
     y = presymbol + y + postsymbol;
     if(sgn) {
          y = "(" + y + ")";
     }
     return(y);
}

in the java:

public String num_format(double x, String presymbol, String postsymbol) throws Exception
{

     String y = "";
     int i = 0;
     int k = 0;    
     boolean sgn = false;
//     System.out.println(x);
     
     sgn = (x < 0);
     x = Math.abs(x);
     x = Math.floor((x * 100) + .5);

     i = 3;
     y = "";
     k = 0;
     while(((i--) > 0) || (x > 0)) {
          y = (x % 10) + y;
          x = Math.floor(x / 10);
          if(i == 1) {
               y = "." + y;
          }
          if (i<1) {
               k ++;
               if (k%3 == 0) {
                    if (x>0) {
                         y = "," + y;
                    }
               }
          }
     }
//     System.out.println(y);    
     y = presymbol + y + postsymbol;
     if(sgn) {
          y = "(" + y + ")";
     }
     return(y);
}

when i try:
System.out.println(num_format(1000, "$", ""));

in the javascript is no problem can get this $1,000, but in the java, i got this answer:
$1.0,0.00.00.0.0.00.0

Can someone help me fix,thanks.
0
weesiong
Asked:
weesiong
1 Solution
 
umangjoshiCommented:
pls use DecimalFormat as follows:

java.text.DecimalFormat df = new java.text.DecimalFormat("###,##0.00");
String formated_number = df.format(1000);
0
 
gwang77Commented:
the problem is at
y = (x % 10) + y;
x%10, at javascript, it will return 0
at java, it will return 0.0, a double type.
change it to the follow is ok.
y = (int)(x % 10) + y;
0
 
weesiongAuthor Commented:
Thanks for your fast response.

Best Regards,
Wee Siong
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now