0

Hello there I want to format a float to german notation like this:

float(12.0) => 12

float(12.7) => 12,7

float(12.23) => 12,23

float(1234) => 1.1234

float(1234.567) => 1.234,567

To achieve this I am trying to use number_format() with an unknown number of decimals:

First try:

number_format($float,0,",",".");

Result not satysfying:

float(12.7) => 13

Next try:

$tr = rtrim(number_format($float,30,",","."),"0");
if(substr($tr,-1)===USS_DM) {
   return rtrim($tr,USS_DM);
}

Result not satysfying and unexpected:

float(13.7) => 13,6999999999999992894572642399

Expected: 13,7

What I try to do here is to number_format the float to 13,7000000000000000000 and trim trailing zeros as well as the decimal mark afterwards if necessary. However for some reason float(13.7) formatted is 13.6999.... etc.

How to format the number in order to get the expected results?

Blackbam
  • 17,496
  • 26
  • 97
  • 150
  • You need to read up on IEEE floating point numbers and their annoying inaccuracies – RiggsFolly Oct 05 '16 at 17:27
  • @RiggsFolly Well I see you are right can you think of a good solution for the number_format problem? Otherwise I reopen and cange the question to how to deal with number_format and float inaccuracies. – Blackbam Oct 05 '16 at 17:34
  • Is this any help http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples – RiggsFolly Oct 05 '16 at 17:37
  • A bit of Googling will get you almost any answer you could possibly want. – RiggsFolly Oct 05 '16 at 17:38
  • @RiggsFolly Temporarily I solved the problem with number_format($float,8,",","."); so that the endresult is most likely to be precise. Can you think of a better solution? – Blackbam Oct 07 '16 at 15:42

0 Answers0