0

I am trying to print result of an expression to 3 decimal places using the below code. it always prints like 5.000 instead of like 5.343. is there something wrong .

number=$((5+50*3/20 + (19*2)/7))
 
printf "%.3f \n" $number
user2636464
  • 685
  • 7
  • 17
  • 1
    Works for me... how do you assign the number? And what's your locale (output of `locale`)? – Benjamin W. Nov 01 '22 at 15:05
  • How is the `number` assigned? – M. Nejat Aydin Nov 01 '22 at 15:06
  • This isn't complete enough to be testable unless you include a specific value for `number` in the question itself. (If it turns out that `number` is incorrectly assigned, that wouldn't be surprising: anywhere you use native shell math instead of floating-point-aware tools would truncate everything after the decimal if it doesn't fail outright). – Charles Duffy Nov 01 '22 at 16:26
  • See https://ideone.com/zMlwfP as an example showing printf working as-intended. (Note `"$number"`, not `$number`; in general, _all_ expansions should be quoted unless you have a specific reason to do otherwise in the immediate context at hand). – Charles Duffy Nov 01 '22 at 16:29
  • 1
    Shell only computes integers. – Léa Gris Nov 01 '22 at 16:38
  • The problem is not the `printf`, but the "expression", which you have not shown. Numeric values in many context in the shell are integer only, and quite likely however you are computing the expression is one of those contexts. – William Pursell Nov 01 '22 at 17:25
  • sorry I have updated with expression example – user2636464 Nov 02 '22 at 03:35
  • 1
    Does this answer your question? [How do I use floating-point arithmetic in bash?](https://stackoverflow.com/questions/12722095/how-do-i-use-floating-point-arithmetic-in-bash). As pointed out by @LéaGris, native bash does only integers. Its not a printf issue. – Nic3500 Nov 02 '22 at 05:53
  • it works by using bc used. – user2636464 Nov 06 '22 at 10:36

0 Answers0