PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label currency. Show all posts
Showing posts with label currency. Show all posts

Friday, August 12, 2022

[FIXED] How to fix a total to 2 decimal places html/javascript

 August 12, 2022     cumulative-sum, currency, decimal, html, javascript     No comments   

Issue

I have the following javascript code to add checkboxes together when selected and produce a total. What do I need to add to the code to get the total to display 2 decimal places always.

<script type="text/javascript">
function checkTotal() {
document.listForm.total.value = '';
var sum = 68.50;
for (i=0;i<document.listForm.choice.length;i++) {
if (document.listForm.choice[i].checked) { 
sum = sum + parseInt(document.listForm.choice[i].value);
}
}
document.listForm.total.value = sum;
}
</script>

Solution

You just need to call toFixed(n) and pass the number of digits after the decimal point:

document.listForm.total.value = sum.toFixed(2);


Answered By - Ibrahim Najjar
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, August 11, 2022

[FIXED] How to Display Currency Format with Separators in EMI Calculator in Flutter

 August 11, 2022     currency, dart, decimal, flutter     No comments   

Issue

I build a EMI calculator in flutter, but my results display as e.g 1250568.00 but wan it to display as N$ 1,250,568.00

i have tries the intl package but get a error on Text(f.format(_tiResults)), as explained how to implement it. also tried the MoneyMask package to no avail.

import 'package:homenet/pages/home_page.dart';
import 'dart:math';

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List _durationTypes = ['Month(s)', 'Year(s)'];
  String _durationType = "Year(s)";
  String _miResult = "";
  String _tiResult = "";
  String _tcResult = "";
  bool _switchValue = true;

  final TextEditingController _principalAmount = TextEditingController();
  final TextEditingController _interestRate = TextEditingController();
  final TextEditingController _loanDuration = TextEditingController();

  _onClear(){
    setState(() {
      _principalAmount.text = "";
      _interestRate.text = "";
      _loanDuration.text = "";
      _miResult = "";
      _tiResult = "";
      _tcResult = "";
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        backgroundColor: new Color(0xFFFA983A),
        title: InkWell(
          onTap: (){
            Navigator.push(context,
              MaterialPageRoute(builder: (context) => new HomePage()));},
          child: Image.asset(
            'assets/images/logo_white.png',
            fit: BoxFit.cover,
          ),
        ),
        elevation: 0.0,
        centerTitle: true,
        actions: <Widget>[
          new IconButton(
            icon: new Icon(Icons.cancel, size: 30,),
            onPressed: () {
              _onClear();
            },
          ),
        ],
      ),
      body: Center(
        child: Container(
          margin: EdgeInsets.all(24),
          child: Column(
            children: <Widget>[
              Container(
                child: TextField(
                  cursorColor: Color(0xFFFA983A),
                  controller: _principalAmount,
                  decoration:
                      InputDecoration(
                  icon: Icon(Icons.monetization_on),
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(25),
                  gapPadding: 5),
                  labelText: "Enter Principal Amount"),

                  keyboardType: TextInputType.numberWithOptions(),
                ),
              ),
              SizedBox(
                height: 12,
              ),
              Container(
                child: TextField(
                  cursorColor: Color(0xFFFA983A),
                  controller: _interestRate,
                  decoration:
                      InputDecoration(
                          icon: Icon(Icons.show_chart),
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(25),
                              gapPadding: 5),
                          labelText: "Interest Rate per Annum %"),
                  keyboardType: TextInputType.numberWithOptions(),
                ),
              ),
              SizedBox(
                height: 12,
              ),
              Row(
                children: <Widget>[
                  Flexible(
                    flex: 3,
                    child: Container(
                      child: TextField(
                        cursorColor: Color(0xFFFA983A),
                        controller: _loanDuration,
                        decoration: InputDecoration(
                            icon: Icon(Icons.date_range),
                            border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(25),
                                gapPadding: 5),
                            labelText: "Loan Duration"),
                        keyboardType: TextInputType.numberWithOptions(),
                      ),
                    ),
                  ),
//                  TODO: ========= SWITCH ================
                  Flexible(
                    flex: 1,
                    child: Column(
                      children: <Widget>[
                        Text(
                          _durationType,
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Switch(
                            activeColor: Color(0xFFFA983A),
                            value: _switchValue,
                            onChanged: (bool value) {
                              print(value);

                              if (value) {
                                _durationType = _durationTypes[1];
                              } else {
                                _durationType = _durationTypes[0];
                              }

                              setState(() {
                                _switchValue = value;
                              });
                            }),
                      ],
                    ),
                  ),
                ],
              ),
              SizedBox(
                height: 12,
              ),
//              TODO: ============== Button ============
              Flexible(
                child: FlatButton(
                  padding: EdgeInsets.fromLTRB(48, 8, 48, 8),
                  onPressed: _handleCalculation,
                  child: Text(
                    "CALCULATE",
                    style: TextStyle(color: Colors.white),
                  ),
                  color: Color(0xFFFA983A),
                ),
              ),
              SizedBox(
                height: 12,
              ),
//              TODO: Results Widget =====================================
              monthlyInstalmentsResult(_miResult),
              SizedBox(
                height: 12,
              ),
              totalInterestResult(_tiResult),
              SizedBox(
                height: 12,
              ),
              totalCostResult(_tcResult),
              SizedBox(
                height: 12,
              ),
              Container(
                child: Text(
                  "Disclaimer* This is just an approximate amount"
                  "and in no way reflect the exact figures, please consult your bank.",
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 10,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _handleCalculation() {
//    TODO: Amortization
    //    TODO: A = Payment amount per period
    //    TODO: P = Initial Principal (Loan Amount)
    //    TODO: r = interest Rate
    //    TODO: n = Total number of payments

    double A = 0.0;
    double I = 0.0;
    double T = 0.0;
    double P = double.parse(_principalAmount.text);
    double r = double.parse(_interestRate.text) / 12 / 100;
    int n = _durationType == "Year(s)"
        ? int.parse(_loanDuration.text) * 12
        : int.parse(_loanDuration.text);

    A = (P * r * pow((1 + r), n) / (pow((1 + r), n) - 1));
    T = (A * n);
    I = (T - P);

    _miResult = A.toStringAsFixed(2);
    setState(() {});
    _tiResult = I.toStringAsFixed(2);
    setState(() {});
    _tcResult = T.toStringAsFixed(2);
    setState(() {});
  }

  Widget monthlyInstalmentsResult(miResults) {

//    var f = new NumberFormat("#,###,###.0#");
//    var f = new NumberFormat("###.0#", "en_US");
    bool canShow = false;
    String _miResults = miResults;

    if (_miResults.length > 0) {
      canShow = true;
    }
    return Container(

        child: canShow
            ? Row(
                children: <Widget>[
                  Text(
                    "Monthly Instalments: ",
                    style: TextStyle(
                      color: Colors.grey,
                      fontSize: 18,
                    ),
                  ),
                  Text(
                    "N\$ ",
                    style: TextStyle(
                      color: Color(0xFFFA983A),
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(
                    _miResult,
                    style: TextStyle(
                      color: Color(0xFFFA983A),
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  )
                ],
              )
            : Row());
  }

  Widget totalInterestResult(tiResults) {
    bool canShow = false;
    String _miResults = tiResults;

    if (_miResults.length > 0) {
      canShow = true;
    }
    return Container(
        child: canShow
            ? Row(
                children: <Widget>[
                  Text(
                    "Total Interest: ",
                    style: TextStyle(
                      color: Colors.grey,
                      fontSize: 18,
                    ),
                  ),
                  Text(
                    "N\$ ",
                    style: TextStyle(
                      color: Color(0xFFFA983A),
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(
                    _tiResult,
                    style: TextStyle(
                      color: Color(0xFFFA983A),
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  )
                ],
              )
            : Row());
  }

  Widget totalCostResult(tcResults) {
    bool canShow = false;
    String _miResults = tcResults;

    if (_miResults.length > 0) {
      canShow = true;
    }
    return Container(
        child: canShow
            ? Row(
                children: <Widget>[
                  Text(
                    "Total Cost: ",
                    style: TextStyle(
                      color: Colors.grey,
                      fontSize: 18,
                    ),
                  ),
                  Text(
                    "N\$ ",
                    style: TextStyle(
                      color: Color(0xFFFA983A),
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(
                    _tcResult,
                    style: TextStyle(
                      color: Color(0xFFFA983A),
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  )
                ],
              )
            : Row());
  }
}

The code is reproducable exactly as i have it inmy app.... I want the results (miResults ,tiResults and tcResults) display in financial/currency format. thank you.


Solution

Try this:

  void _handleCalculation() {
    //    TODO: Amortization
    //    TODO: A = Payment amount per period
    //    TODO: P = Initial Principal (Loan Amount)
    //    TODO: r = interest Rate
    //    TODO: n = Total number of payments

    double A = 0.0;
    double I = 0.0;
    double T = 0.0;
    double P = double.parse(_principalAmount.text);
    double r = double.parse(_interestRate.text) / 12 / 100;
    int n = _durationType == "Year(s)"
        ? int.parse(_loanDuration.text) * 12
        : int.parse(_loanDuration.text);

    A = (P * r * pow((1 + r), n) / (pow((1 + r), n) - 1));
    T = (A * n);
    I = (T - P);

    NumberFormat format = NumberFormat('#,###,###.00');
    setState(() {
      _miResult = format.format(A);
      _tiResult = format.format(I);
      _tcResult = format.format(T);
    });
  }


Answered By - Richard Heap
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How was non-decimal money represented in software?

 August 11, 2022     currency, decimal     No comments   

Issue

A lot of the answers to the questions about the accuracy of float and double recommend the use of decimal for monetary amounts. This works because today all currencies are decimal except MGA and MRO, and those have subunits of 1/5 so are still decimal-friendly.

But what about the software used in U.S. stock markets when prices were in 1/16ths of dollar? The accuracy of binary data types wouldn't have been an issue, right?

Going further back, how did pre-1971 British accounting software deal with pounds, shillings, and pence? Did their versions of COBOL have a special PIC clause for it? Were all amounts stored in pence? How was decimalisation handled?


Solution

PL/I had a type specifically for British currency - I don't know about COBOL. The British currency at one time incorporated farthings, or a quarter of a penny; I'm not sure though that computers had to deal with those, just with half pennies or ha'pennies.

Accurate accounting usually uses special types - representing decimals exactly. The new IEEE 754 has support for floating-point decimals, and some chips (notably IBM pSeries) have such support in hardware.



Answered By - Jonathan Leffler
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why decimal holding value like 0.219e3 instead of 219.0 which I want

 August 11, 2022     currency, decimal, ruby, ruby-on-rails     No comments   

Issue

I am using Ubuntu 18.04.2 LTS and ruby 2.5.1p57 and rails 5.2.3

I have model like:

class CreatePriceLists < ActiveRecord::Migration[5.2]
  def change
    create_table :price_lists do |t|
      t.integer :number_of_pallets
      t.decimal :net_rabate, precision: 5, scale: 2
      t.decimal :net_logistic, precision: 5, scale: 2

      t.timestamps
    end
  end
end

and in my seeds I am trying to seed my database with :

 CreatePriceLists.create([
{
    number_of_pallets: 2,
    net_rabate: 23.00,
    net_logistic: 25.00
}, {
    number_of_pallets: 5,
    net_rabate: 21.00,
    net_logistic: 35.00   
}

and when I am calling rails db:seed in database I can see CreatePriceList objects like this:

#<CreatePriceLists id: 10, number_of_pallets: 2 net_rabate: 0.209e3, net_logistic: 0.29e3, created_at: "2019-08-14 20:36:50", updated_at: "2019-08-14 20:36:50">

I was looking for examples how to store price/money/currency in database and all examples saying that I have to use decimal

So, right now I change column type to float and everything works like it should, but I would like to change to decimal if that is the best option, but need to know what is going on.


Solution

When the column type is Decimal, the adapter is probably converting the value to a BigDecimal object on ruby.

require 'bigdecimal'

BigDecimal(219)
=> 0.219e3

The number is actually "219", it's just cientific notation (0.219 x 10^3).

BigDecimal(219) == 219
=> true

BigDecimal(219).to_f
=> 219.0


Answered By - arieljuod
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to format double with DecimalFormatSymbols and currency?

 August 11, 2022     android, currency, decimal, double, formatting     No comments   

Issue

My result should look like this: $100 00,99 I managed to format the number as I need, but without the currency. I managed to get the currency separately, but can't get the two together. For the numbering format, I used DecimalFormatSymbol as in the answer to this question.

 private fun formatValue(value: Double, formatString: String): String {
     val formatSymbols = DecimalFormatSymbols(Locale.ENGLISH)
     formatSymbols.decimalSeparator = ','
     formatSymbols.groupingSeparator = ' '
     val formatter = DecimalFormat(formatString, formatSymbols)
     return formatter.format(value)
 }

 formatValue(amount ,"###,###.00")

For the currency I used this code:

fun getFormattedCurrency(currency: String, amount: Double): String {
     val c = Currency.getInstance(currency)
     val nf = NumberFormat.getCurrencyInstance()
     nf.currency = c
     return  nf.format(amount)
}

How can I combine the two?


Solution

Hope this helps you.

    val decimalFormatSymbols = DecimalFormatSymbols().apply {
        decimalSeparator = ','
        groupingSeparator = ' '
        setCurrency(Currency.getInstance("AED"))
    }


    val decimalFormat = DecimalFormat("$ #,###.00", decimalFormatSymbols)
    val text = decimalFormat.format(2333222)
    println(text) //$ 2 333 222,00


    val decimalFormat2 = DecimalFormat("¤ #,###.00", decimalFormatSymbols)
    val text2 = decimalFormat2.format(2333222)
    println(text2) //AED 2 333 222.00

Notifiy that if you use ¤ instead of specific currency symbol like $,€ it will use a symbol according to currency instance you create. Also you can get more info from docs. https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

Also you can find ISO 4217 codes in https://en.wikipedia.org/wiki/ISO_4217



Answered By - toffor
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 10, 2022

[FIXED] How does Python babel round numbers?

 August 10, 2022     currency, decimal, python, python-babel, rounding     No comments   

Issue

I'm building a financial website with the Flask framework and I'm currently writing unit tests for it. I'm using the Babel package to format money amounts and I hit upon rather strange rounding behaviour. I would expect rounding to be up in case of a 5, or to at least be consistent. But look at this:

>>> from decimal import Decimal
>>> from babel.numbers import format_currency
>>> print format_currency(Decimal('.235'), 'EUR', locale='nl_NL')
€ 0,24
>>> print format_currency(Decimal('.245'), 'EUR', locale='nl_NL')
€ 0,24

Why is this so, and more importantly; how can I solve this?

ps: I would prefer .245 to be rounded up to .25

[EDIT]

I went looking for the source, which links to some other pieces of code. But I can't really figure out what's wrong there and why it seems to randomly round up or down. Anybody any idea?


Solution

If you follow the code through to apply you can see a reference to a bankersround procedure, which tells us what we need to know. Babel is using the bankers round method of rounding, which rounds to the nearest even number on 5. So, .245 and .235 round to .24 as .24 is the closest even value for each. Values above and below 5 round normally.



Answered By - paidhima
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, August 7, 2022

[FIXED] how to store bitcoin and other currencies in mysql database

 August 07, 2022     bitcoin, currency, decimal, mysql     No comments   

Issue

I try to make payment system. Customers can make purchases with bitcoin or other curriencies like (USD,EUR) i have a decimal amount column with (16,8), for bitcoin amounts it works normally, but when i try to put usd value for example 100 usd , it becomes 100.00000000 , my question is should store amount like this ? use same decimal column for bitcoin and other currencies? is it bad for performance when counting all records? or should i have multiple column for bitcoin decimal(16,8) and for other currencies decimal(10,2) , show me a way - please consider millions of records when you answering.


Solution

There are two aspects of performance -- speed and space. Speed is usually not a concern because fetching rows is far more costly than the effort to manipulate decimal/double/etc. Space can be a concern (and lead to slowdowns) if you are talking about a billion rows.

Rule of Thumb: DECIMAL(m,n) take about m/2 bytes. In the case of (16,8), it takes exactly 8 bytes.

DOUBLE takes 8 bytes; BIGINT: 8 bytes. Etc.

Don't use VARCHAR for numeric values, especially if you need to sort them.

FLOAT and DOUBLE incur an extra rounding (decimal to/from binary), leading to possible round-off errors, especially when adding up lots of numbers.

I don't know for sure, 8 decimal places is the official max needed for Bitcoin, and is more than enough for any other currency. 4 is the most I have heard of for a currently used currency. (Pounds/Shillings/Pence is no longer in use.)

DECIMAL(16,8) overflows at 100,000,000 dollars/euros/whatever. Make sure that is enough. DECIMAL(17,8) also takes 8 bytes, giving you a Billion max. So you may as well use 17 instead of 16.

Back to the question... There is no 'perfect' answer.



Answered By - Rick James
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I format decimal property to currency?

 August 07, 2022     c#, currency, decimal     No comments   

Issue

I want to format a decimal value as a currency value.

How can I do this?


Solution

Properties can return anything they want to, but it's going to need to return the correct type.

private decimal _amount;

public string FormattedAmount
{
    get { return string.Format("{0:C}", _amount); }
}

Question was asked... what if it was a nullable decimal.

private decimal? _amount;

public string FormattedAmount
{
    get
    {
         return _amount == null ? "null" : string.Format("{0:C}", _amount.Value);
    }
}  


Answered By - Robaticus
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 24, 2022

[FIXED] How to get current Mastercard rates (buy/sell currency)?

 July 24, 2022     api, currency, json, mastercard, xml     No comments   

Issue

I need to check current Mastercard rates for multiple currencies in my app but I can't found any correct API to do this.

In the same time, large count of sites has regular updates for this rates. Can someone tell me where can I get these rates (buy and sell currency) information?


Solution

2022 Update

Mastercard's public APIs do not include one for currency exchange rates, but they do have a Currency Conversion Tool:

Source: MasterCard API showcase forum answer by Brett Thomson.



Answered By - kjhughes
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, July 19, 2022

[FIXED] How to format a Currency string to Integer?

 July 19, 2022     c#, currency, formatting, integer     No comments   

Issue

I have a string with currency format like $35.00 and this has to be converted to 35.

Is that possible to retrieve using String.Format{ }


Solution

int value = int.Parse("$35.00", NumberStyles.Currency);

Should give you the answer you need.

However, a value like $35.50 converted to an integer will likely not return what you want it to, as Integers do not support partial (decimal) numbers. You didn't specify what to expect in that situation.

[EDIT: Changed double to decimal which is safer to use with currency]

If you want to get a value of 35.5 in that situation, you might want to use the decimal type.

decimal value = decimal.Parse("$35.00", NumberStyles.Currency);

Note that you have to be very careful when dealing with money and floating point precision.



Answered By - Khalos
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing