0

Consider I have some double number, I want to truncate it(not round) and leave 4 digits after floating point(exactly 4, always 4, if there are not enough digits - add zeros). Examples:

2344.4234934 -----> 2344.4234
1.345584 -----> 1.3455
34.3434 -------> 34.3434
0.123 ------> 0.1230
1 ---------> 1.0000

I'm using java language, and I'm asking for some built-in functions. I have a solution already but it's too complicated, may be there is an elegant one.

Petrovskij
  • 13
  • 4
  • Could you please show your existing solution so we do not suggest that? – David Waters Jun 10 '15 at 00:23
  • i used DecimalFormat with floor rounding mode, then I added missing zeros in old-school way + "0" – Petrovskij Jun 10 '15 at 00:27
  • 1
    What format string did you use with the `DecimalFormat`? That should be all you need to use. You shouldn't need to do anything else with the string once it's returned. – Ian McLaird Jun 10 '15 at 00:29
  • possible duplicate of [Are there any functions for truncating a double in java?](http://stackoverflow.com/questions/1976809/are-there-any-functions-for-truncating-a-double-in-java) – David Waters Jun 10 '15 at 00:30

1 Answers1

2

Try this

DecimalFormat fmt = new DecimalFormat("0.0000");
fmt.setRoundingMode(RoundingMode.DOWN);
String s = fmt.format(myDouble);
Ian McLaird
  • 5,507
  • 2
  • 22
  • 31