1

I have the following code that converts my satoshi value to a bitcoin value:

private static double satToBtc(long sat){
        return sat / Math.pow(10, 8);
    }

now I have the following code executing:

            double btc = satToBtc(value);
            User user = User.getUserByDepositBitcoinAddress(address);
            if (user == null) return;
            try (Connection connection = MySQL.getConnection();
                 ...
 
                statement.setDouble(3, btc);
                ...

                return;
            }

now what is happening is, I am given the satoshi amount of 100,000 which is worth 0.001 (the function returns exactly 0.001) bitcoin but when I store it in my mysql table it sets the value as: 0.00000001.

How do I go about fixing this?

EDIT - UPDATED satToBtc function:

    private static BigDecimal satToBtc(long sat){
        return new BigDecimal(sat / Math.pow(10, 8));
    }
Loran
  • 13
  • 5
  • 2
    "the function returns exactly 0.001" - no it doesn't. It *can't*, because the value 0.001 can't be represented exactly in a `double`. I suspect you'd be better off using `BigDecimal`. – Jon Skeet Sep 06 '20 at 11:26
  • Oh, okay one moment let me give it a shot. – Loran Sep 06 '20 at 11:33
  • 1
    And what mysql table column type are you using? This should be `decimal` also. – danblack Sep 06 '20 at 11:34
  • @JonSkeet what would be the SQL datatype for bigdecimal? I tried the Decimal data type but it just returned `0`, when I run the satToBtc function with a value of `100000` using big decimal it returns: `0.001`, so it works, but i just don't know the mysql datatype. – Loran Sep 06 '20 at 11:42
  • @Progman in all honesty, that just confused me. – Loran Sep 06 '20 at 11:43
  • @JonSkeet it actually returned `0.001000000000000000020816681711721685132943093776702880859375`, so you where right about that, now its just the SQL issue. – Loran Sep 06 '20 at 11:47
  • It sounds like you need to go off and do some research about using BigDecimal with MySQL - you can do that *entirely separately* from this code. Just create a table with a single column, and write a tiny console app that just inserts a hard-coded BigDecimal into it. Once you've got *that* working, you can come back to this. – Jon Skeet Sep 06 '20 at 11:47
  • By 'sql issue' I mean the fact its not storing properly. – Loran Sep 06 '20 at 11:47
  • @Loran Save the value as satoshi and convert it only when displaying it to the user. That way you don't have to do floating math operations, which can be tricky. – Progman Sep 06 '20 at 11:50
  • @Progman you're the smartest man alive. – Loran Sep 06 '20 at 11:51
  • @Loran See other questions like https://stackoverflow.com/questions/693372/what-is-the-best-data-type-to-use-for-money-in-c on how to work with money values. – Progman Sep 06 '20 at 11:52
  • THIS ISSUE HAS BEEN FIXED THANKS TO @Progman (and Jon Skeet), thanks for your help guys. – Loran Sep 06 '20 at 13:42

0 Answers0