0

I state that I am new with Flutter.

I would like to do 50/2

I try with the DartPad

print((50/2).toString());     // return 25

I try the Flutter debugger build that I installed in a Pixel 4 emulator

print((50/2).toString());     // return 25.0

Why does the ".0" return? Was I wrong to do something? Is everything normal and is it kind of a code conversion?

How can I get it without ".0"?

ps. This is a case but I'm also talking about more complex situations where instead of doing a precise division, I could divide two variables (which maybe are not int but double) and / or do other operations. I've already evaluated things like toStringAsPrecision, it works for the single case but messes up the string if it contains true decimals.

ps2. The only solution that came to my mind is to replace the .toString with a custom extension method that eliminates superfluous zeroes (also considering the decimal point)

Francesco - FL
  • 603
  • 1
  • 4
  • 25
  • When running in Dartpad, your dart is converted to Javascript, where integer / integer-that-happens-to-be-a-factor yields an int. When running in the Dart VM / always yields a double. Hence the difference you see. To perform integer division in the VM use `~/`. Or use `floor()` and friends on the double as appropriate. – Richard Heap Jul 30 '22 at 20:45
  • The problem in my case is that if instead of 50/2, I have a/b, where a and b are numbers that can be both decimal and integer, and whose fraction can be both a decimal and an integer, use the methods you said would remove decimals from the result. Maybe then the "extension method" I mentioned is the only way to delete that '.0' only when it is there. – Francesco - FL Jul 30 '22 at 20:54
  • yes - replace `.0` at the end with '' – Richard Heap Jul 30 '22 at 21:15

1 Answers1

0

If you want to skip the .0 you should use truncating division a~/b. Answer is explained here : How to do Integer division in Dart?

  • As I wrote in the "ps", I might have different numbers like 50/2 or like a / b or like 51/2. Using ~ / would delete important decimals if there were any – Francesco - FL Jul 30 '22 at 21:03
  • If you'd like to check if there are numbers after the decimal point that are significant you can use the modulo operator with the number one. (a/b) %1 , and then check to the nearest x decimal place you require and if the decimals are significant to you you can print them else truncate. – Aly_ElAshram Jul 31 '22 at 21:10
  • if( (a/b) %1 > 0.001 ) { //keep the decimals print(a/b); } else{ print(a~/b); } – Aly_ElAshram Jul 31 '22 at 21:11
  • It can be an alternative. However I preferred to work on the string, so I do the toString and wonder if the string ends in '.0'. If so I remove it, otherwise I leave it. – Francesco - FL Aug 01 '22 at 01:18