0
awk '{printf "%d\n", (1234.12*100)}' <<<""

outputs

123411

It is supposed to be 123412.

Awk version: GNU Awk 4.1.4, API: 1.1 (GNU MPFR 4.0.1, GNU MP 6.1.2)

What am I missing?

EDIT: Weird, I did more tests:

$ awk '{printf "%d\n", (0.12*100)}' <<<""
12
$ awk '{printf "%d\n", (1.12*100)}' <<<""
112
$ awk '{printf "%d\n", (12.12*100)}' <<<""
1212
$ awk '{printf "%d\n", (123.12*100)}' <<<""
12312

so far all good.

But then get wrong:

$ awk '{printf "%d\n", (1234.12*100)}' <<<""
123411

Other forms work:

$ awk '{print (1234.12*100)}' <<<""
123412
$ awk '{printf "%.0f\n", (1234.12*100)}' <<<""

outputs 123412 correctly.

shellter
  • 36,525
  • 7
  • 83
  • 90
osexp2000
  • 2,910
  • 30
  • 29
  • 3
    Try `awk '{printf "%.12f\n", (1234.12*100)}' <<<""`. See [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Guy Incognito May 29 '23 at 15:56
  • Output is 123411.999999999985 – osexp2000 May 29 '23 at 16:02
  • But `awk '{printf "%.0f\n", (1234.12*100)}' <<<""` outputs `123412` – osexp2000 May 29 '23 at 16:03
  • Why is that surprising? – Guy Incognito May 29 '23 at 16:04
  • Both `awk '{print (1234.12*100)}' <<<""` and `awk '{printf "%.0f\n", (1234.12*100)}' <<<""` work, why the printf "\d" does not? – osexp2000 May 29 '23 at 16:07
  • `%d` truncates the number, the others round it – Guy Incognito May 29 '23 at 16:08
  • I know there is some precision loss during storing decimal number with binary floating number, but the issue I encountered seems should not happen. – osexp2000 May 29 '23 at 16:08
  • @GuyIncognito Sure %d truncates the number, 1.2 -> 1, I understand, but obviously awk know `(1234.12*100)` is `123412`, so it not about truncating, `123412` should output `123412` by %d. – osexp2000 May 29 '23 at 16:09
  • Seems be a bug of awk. – osexp2000 May 29 '23 at 16:10
  • `awk '{a=(1234.12*100); printf "%d\n", a}'` also outputs wrong `123411`. – osexp2000 May 29 '23 at 16:12
  • Why does `awk '{printf "%d\n", (123.12*100)}' <<<""` works? – osexp2000 May 29 '23 at 16:12
  • 3
    `1234.12*100` is `123411.999999999985...`, you [saw it yourself](https://stackoverflow.com/questions/76358711/unbelievable-awk-rounding-a-float-to-integer-got-weird-result-123-12100-12#comment134648333_76358711). 123411.999... truncated is 123411. `123.12*100` is exactly 12312. It's definitely not a bug. – Guy Incognito May 29 '23 at 16:16
  • You should read https://www.gnu.org/software/gawk/manual/gawk.html#Arbitrary-Precision-Arithmetic and https://www.gnu.org/software/gawk/manual/gawk.html#Round-Function. – Ed Morton May 30 '23 at 15:35
  • Thank you all a lot. Understood. Just wonder why my comment of "Got it ...." was deleted? I remember I have replied. – osexp2000 May 31 '23 at 06:34

0 Answers0