4

I have code in Free pascal, I have real number 3.285714287142857E+000 from a/b.

program threedigits;
var a,b:real;

begin
a:=23;
b:=7;
writeln(a/b);
end.

How to change the number to three digits after comma (3.286)?

Jongware
  • 22,200
  • 8
  • 54
  • 100
  • Multiply by 1000, round, and divide by 1000. –  Jan 10 '17 at 09:35
  • 1
    @Yves No, don't do that! You need to learn about representability for floating point values. – David Heffernan Jan 10 '17 at 11:05
  • @DavidHeffernan: are you kidding ? –  Jan 10 '17 at 11:38
  • @Yves No I am not kidding. Perhaps you aren't aware that `3.286` cannot be represented in a binary floating point data type. I suppose you could switch to integer all the way after the round, but why add all that complexity and arithmetic when you can achieve the same using simple presentation formatting methods? – David Heffernan Jan 10 '17 at 11:39
  • @DavidHeffernan: haha. The OP is asking to return 3.286, in what way is it harmful to compute the closest representation ? –  Jan 10 '17 at 11:41
  • 1
    @YvesDaoust No, the question wants `'3.286'`. That is text. Since you have to convert to text, and since you have to specify 3dp, you can do so directly at no extra cost. Your approach requires three floating point operations for no gain whatsoever. – David Heffernan Jan 10 '17 at 11:42
  • @DavidHeffernan: now I understand your reaction. The OP should have asked "How to change the output to...", not "the number". –  Jan 10 '17 at 11:44
  • 1
    OK, but that could have been inferred from the `Writeln`. – David Heffernan Jan 10 '17 at 11:45
  • 1
    @David is right, Do not change the number, change the output format. – Rudy Velthuis Jan 10 '17 at 14:44
  • FYI, the edit you rolled back was totally valid. You even approved it yourself! So I rolled it back. – Jongware Jan 26 '17 at 09:48

1 Answers1

6

Use 0:3

var a,b:real;

begin
a:=23;
b:=7;
writeln(a/b:0:3);

readln;
end.
  • 1
    the integer after the first colon is the length you desire BEFORE the comma. If you would increase the number, it will add spaces at the start of the result. This is used to align your numbers nicely when not using a GUI. The integer after the second colon is the length for the digits after the comma. – Cealeth Jan 12 '17 at 15:38