java - Convert BigDecimal to String with no trailing zeros -



java - Convert BigDecimal to String with no trailing zeros -

this question has reply here:

why new bigdecimal(“0.0”).striptrailingzeros() have scale of 1? 1 reply

i want remove trailing zeros bigdecimal , print it. trailingzeros method not working (i) expected.

bigdecimal = new bigdecimal("-11111111111111111111111111111111111111.111111111111111111111111111111"); bigdecimal b = new bigdecimal("11111111111111111111111111111111111111.111111111111111111111111111111"); bigdecimal c = a.add(b); system.out.println(c); system.out.println(c.toplainstring()); c = c.striptrailingzeros(); system.out.println(c); system.out.println(c.toplainstring());

the output of code is:

0e-30 0.000000000000000000000000000000 0e-30 0.000000000000000000000000000000

i result of "0".

what using decimalformat create formatted string according requirements.

example

bigdecimal bd = new bigdecimal(2324.0011); decimalformat format = new decimalformat("#,##0.00"); string formatted = format.format(bd); // string contains "2,324.00"

or

bigdecimal bd = new bigdecimal(2324.0011); decimalformat format = new decimalformat("#,##0"); string formatted = format.format(bd); // string contains "2,324"

or values provided:

bigdecimal = new bigdecimal("-11111111111111111111111111111111111111.111111111111111111111111111111"); bigdecimal b = new bigdecimal("11111111111111111111111111111111111111.111111111111111111111111111111"); bigdecimal c = a.add(b); decimalformat format = new decimalformat("#,##0"); system.out.println(format.format(c)); // prints "0"

you strip remaining trailing zeros regex (?<=\d)\.?0+(?![\d\.]), example:

string value = "10000.343999000"; string stripped = value.replaceall("(?<=\\d)\\.?0+(?![\\d\\.])", ""); // 10000.343999

java string-formatting bigdecimal

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -