0

everyone , i want to know anyone create function or package like _ceil or _round() same as lodash JavaScript utility library ? i need it , thank in advance

reference link : lodash

Heng YouSour
  • 133
  • 1
  • 11
  • Don't know this JavaScript library but what is wrong using the [`ceil()`](https://api.dart.dev/stable/2.12.4/dart-core/double/ceil.html) and [`round()`](https://api.dart.dev/stable/2.12.4/dart-core/double/round.html) methods on the [`double`](https://api.dart.dev/stable/2.12.4/dart-core/double-class.html) type in Dart? – julemand101 Apr 25 '21 at 09:38
  • ciel() & round() in dart it doesn't have precision combine with it you can check _ceil() & round() lodash . Example : _.ceil(number, [precision=0]) link : [_ciel()](https://lodash.com/docs/4.17.15#ceil) @julemand101 – Heng YouSour Apr 25 '21 at 14:41
  • @julemand101 what i mean is ceil combine with precision :) – Heng YouSour Apr 25 '21 at 14:44
  • I don't know how lodash works, but what you want doesn't make sense for floating-point numbers. That is, you can't have a specific precision in base-10 using a system that uses base-2. As a basic example, the decimal number 0.3 cannot be exactly represented in binary floating-point. (For more details, see [Is floating point math broken?](https://stackoverflow.com/questions/588004/)) You can look into using [`package:decimal`](https://pub.dev/packages/decimal), which provides operations for working with arbitrary precision base-10 numbers. – jamesdlin Apr 26 '21 at 01:01
  • @jamesdlin it isn't what i want, here example: ```_.ceil(6.004, 2); // => 6.01 _.ceil(6040, -2); // => 6100``` – Heng YouSour Apr 28 '21 at 14:06

1 Answers1

0

As I explained in comments, what you want doesn't make sense for IEEE-754 floating-point numbers. That is, you can't have a specific precision in base-10 using a system that uses base-2. As a basic example, the decimal number 0.3 cannot be exactly represented in binary floating-point. (For more details, see Is floating point math broken?)

package:decimal provides operations for working with arbitrary precision base-10 numbers, so you can use that to pretty easily create your own implementation:

import 'package:decimal/decimal.dart';

Decimal _multiplier(int precision) => Decimal.fromInt(10).pow(precision.abs());

Decimal ceil(Decimal n, [int precision = 0]) {
  var multiplier = _multiplier(precision);
  return (n * multiplier).ceil() / multiplier;
}

void main() {
  print(ceil(Decimal.parse('4.006'))); // Prints: 5
  print(ceil(Decimal.parse('6.004'), 2)); // Prints: 6.01
  print(ceil(Decimal.parse('6040'), -2)); // Prints: 6100
  print(ceil(Decimal.parse('0.1') + Decimal.parse('0.2'), 1)); // Prints: 0.3
}

Implementing equivalent functions for floor and round should be similar.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204