Edward
Edward

Reputation: 1377

How to truncate number before decimal?

Below code truncate number after decimal

 NumberFormat blah= new DecimalFormat("#.##");

But I want to truncate extra zeros from the number which are present before number

eg

0000000000000.00  -> 0.00
00000100000.00 -> 100000.00
000000175000.00 -> 175000.00

Upvotes: 0

Views: 865

Answers (2)

Jon Lin
Jon Lin

Reputation: 143906

You don't need the number format unless you want to print it out that way. Just take the string and use Double.parseDouble(), then print the format:

// "#.00" always shows 2 digits after decimal, "#.##" is optional if zeros are after decimal
NumberFormat blah = new DecimalFormat("#.00");

String s = "00000100000.00";
System.out.println(blah.format(Double.parseDouble(s)));

Upvotes: 1

kapandron
kapandron

Reputation: 3671

BigDecimal myNumber = new BigDecimal("00000000175000.000000");
BigDecimal truncatedNumber = myNumber.setScale(3, BigDecimal.ROUND_HALF_UP);

Upvotes: 1

Related Questions