0

I want to write 5 digit zip code to an Excel file. for ex. for number 01803 if I don't convert it to string it will store it as 01803 string but shows an error on excel file.So I want to store it as Big Decimal number without stripping the leading 0's.but Big decimal by default strips it for the current case.

In excel, when I store it as string and convert that to number in excel it will strip the leading zero's

    Address address = new Address();
    address.setPostalCode("01803");
    String postCode = address.getPostalCode();
    if(postCode.matches("^[0-9]*$") && postCode.length() > 2){
        if(postCode.charAt(0) == '0'){
            System.out.println(postCode.toString());    
        } else {
            System.out.println(new BigDecimal(postCode).doubleValue());                         
        }
    }else {
        System.out.println(address.getPostalCode());
    }
vk1
  • 166
  • 6
  • 15
  • Write it as `'01803`, i.e. with a leading `'`. – Andy Turner Mar 09 '17 at 22:02
  • But it will it as '01803 in excel column? – vk1 Mar 09 '17 at 22:05
  • When you import the (single column) CSV file into Excel using the Text Import Wizard, just specify that the column is `Text`. – Andreas Mar 09 '17 at 22:08
  • I want to store it as number not text – vk1 Mar 09 '17 at 22:25
  • 1
    "I want to store it as number not text" Unfortunately you can't do it. You either convert string to number and at this point loose original representation altogether including leading and trailing zeroes, exponential form, group separators, etc. OR you store the string as is and convert it to the number on demand. Of course you can store the value in both representations at once. It might help if you say why you want to store them as BigDecimal. For now this looks like a [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – SergGr Mar 10 '17 at 02:53

1 Answers1

0

Can give this a try

 String abc = 0003;
 formatToCVSValue(abc);

    public static String formatToCVSValue(String s)
        {
            if(s==null || !hasLength(s))
                return "";
            else
            {
                return "\"=\"\""+s+"\"\"\"";
            }
        }

When open in excel, you will see exactly 0003 instead of '0003

John Joe
  • 12,412
  • 16
  • 70
  • 135