-1

I have a requirement where I have to publish a float/decimal number(not string) with fixed decimal digits in json

For eg. If I have a float value as 10.12345, the output json should look like:

{
   "number": 10.123450
}

on the other hand if I have 10.12345678 , this should be mapped to output json (without rounding off):

{
   "number": 10.123456
}

I have tried with format but it produces result as String and If I again cast it to float it will lose the trailing 0's or rounding off the number.

Is it achievable without losing the datatype from number to String.

Regards,

Manish
  • 1,274
  • 3
  • 22
  • 59
  • 1
    Round down first? – Brian61354270 Aug 24 '23 at 13:49
  • 2
    The float *values* of 10.123450 and 10.12345 are exactly the same. What you request doesn’t make sense - a float value doesn’t have a specific representation so it cannot preserve one. Note that any API, script or similar expecting the JSON to include float values *with meaningful format* is equally broken. – MisterMiyagi Aug 24 '23 at 13:52
  • 1
    Does this answer your question? [round down to 2 decimal in python](https://stackoverflow.com/questions/41383787/round-down-to-2-decimal-in-python) – trincot Aug 24 '23 at 14:28
  • @trincot yes for one case, but there's another scenerio on where I have to append 0 where decimal digits are less than specific number let's say 6 – Manish Aug 25 '23 at 05:09
  • 1
    Why? There is no good reason why you want to append 0. Read the comment from MisterMiyagi. See duplicate [How to display BigDecimal number with trailing zero in a JSON (not as string)?](https://stackoverflow.com/q/48662635/5459839) – trincot Aug 25 '23 at 05:41
  • @trincot yeah I understand that. Just tried to figure out there's way. – Manish Aug 25 '23 at 06:12
  • 1
    Sorry, but if you want to figure out there is a way (to pad the decimal part with zeroes), you are actually indicating you don't understand this point. Numbers are numbers. They are not their representations. – trincot Aug 25 '23 at 06:14
  • @trincot that's what I said that I understood. Earlier I thought to figure out if there's a way when I posted this question. – Manish Aug 25 '23 at 06:29

0 Answers0