-1

I would like to change the precision of double value.

For example:

I need to get 3.14 from 3.141592653589793

I expect function like:

scale :: Int -> Double -> Double
> scale 2 3.141592653589793
3.14
> scale 3 3.141592653589793
3.141

Also, I would like to be able to choose the rounding strategy.

round :: ROUND -> Int -> Double -> Double
> round ROUNDUP 5 3.141592653589793
3.1416
  • How can I do it?
  • How can I apply the rounding strategy for it?

P.S.:

Expected behavior in Java should setScale of BigDecimal: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html

mkUltra
  • 2,828
  • 1
  • 22
  • 47
  • please share some example code with your desired outcome. I really don't know what you are asking for – Robin Zigmond Mar 28 '19 at 12:53
  • Possible duplicate of [Round number to specified number of digits](https://stackoverflow.com/questions/12450501/round-number-to-specified-number-of-digits) – mkrieger1 Mar 28 '19 at 12:58
  • Do you want to round at display time, or do calculations with an equally-precise number that is a small modification of another? ie, do you want a function with the type `Double -> String` or a function with the type `Double -> Double`? – Carl Mar 28 '19 at 13:00
  • @Carl Yes, I am looking for Double -> Double function – mkUltra Mar 28 '19 at 13:16
  • @MichaelLitchard You are wrong – mkUltra Mar 28 '19 at 13:30
  • I can have my mind changed. How am I wrong? Where is your attempt? –  Mar 28 '19 at 14:20
  • I stuck with this problem from yesterday. I made some google and stackoverflow requests. I took a time read Prelude, searched for "scale" and "precision" on hoogle. Found something similar like https://hackage.haskell.org/package/rounded-0.1.0.1/docs/Numeric-Rounded.html, and then I decided to ask from someone with more experience to get a better solution. For sure I am wasn't clear with the question. I followed suggestions to clarify. – mkUltra Mar 28 '19 at 15:04
  • fair enough. removed downvote. –  Mar 28 '19 at 16:04

1 Answers1

2

The correct Haskell analog of Java's BigDecimal is Fixed, not Double. You may convert between different precisions via realToFrac.

Daniel Wagner
  • 145,880
  • 9
  • 220
  • 380