Флэш-форматер AS3 для Flash - PullRequest
       18

Флэш-форматер AS3 для Flash

1 голос
/ 24 апреля 2011

Мне нужна помощь в расширении правильной строки ?? отформатировать мои числовые шаговые и / или текстовые поля отображения в форматированной валюте. Вы можете скачать FLA с CS5 flash FLA ЗДЕСЬ . Спасибо

 /* start application */
import flash.geom.Matrix;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.text.TextField;
import flash.net.URLLoader;
import flash.globalization.CurrencyFormatter;


//comboBox, I populate values displayed to users

    this.comptype.addItem ( { label: "clerical" } );
    this.comptype.addItem ( { label: "concrete" } );
    this.comptype.addItem ( { label: "demolition" } );
    this.comptype.addItem ( { label: "electricians" } );
    this.comptype.addItem ( { label: "excavation" } );
    this.comptype.addItem ( { label: "HVAC/Plumbing" } );
    this.comptype.addItem ( { label: "oil and gas" } );
    this.comptype.addItem ( { label: "road/bridge construction" } );
    this.comptype.addItem ( { label: "roofing" } );
    this.comptype.addItem ( { label: "sewer construction" } );
    this.comptype.addItem ( { label: "truck driving" } );
    this.comptype.addItem ( { label: "warehousing" } );

this.comptype.addEventListener (Event.CHANGE, selectOrder); 
function selectOrder (event:Event) : void

    {
        if (this.comptype.selectedItem.label == "clerical") this.orderTotal.text = ("3.00");
        if (this.comptype.selectedItem.label == "concrete") this.orderTotal.text = ("8.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "demolition") this.orderTotal.text = ("10.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "electricians") this.orderTotal.text = ("5.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "excavation") this.orderTotal.text = ("8.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "HVAC/Plumbing") this.orderTotal.text = ("6.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "oil and gas") this.orderTotal.text = ("13.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "road/bridge construction") this.orderTotal.text = ("10.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "roofing") this.orderTotal.text = ("18.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "sewer construction") this.orderTotal.text = ("9.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "truck driving") this.orderTotal.text = ("13.00"); //make sure my values match the above values EXACTLY
        if (this.comptype.selectedItem.label == "warehousing") this.orderTotal.text = ("7.00"); //make sure my values match the above values EXACTLY

    }
this.outline.calcBtn.addEventListener (MouseEvent.CLICK, goCalc);
function goCalc (Event:MouseEvent) : void

            {
        this.outline.annualSavings.text = (this.staffrate.value-(14.15 + parseInt(this.orderTotal.text)))*this.payroll.value;
        //this.outline.docCostMonth.text = (this.timesPerDay.value * 260) / 12 * this.docProcCost.value;
        //this.outline.docCostYear.text = (this.outline.docCostMonth.text *12);
        //this.outline.annualSavings.text = ((this.procAutoSaving.value * this.outline.docCostYear.text) / 100);
        }


var cf:CurrencyFormatter = new CurrencyFormatter( "en_US" );
this.payroll.value = this.payrollOut;
cf.format( this.payrollOut.text );  //??

Ответы [ 3 ]

2 голосов
/ 15 июля 2011

Привет, надеюсь, это поможет,

myTextField1.text = formatCost(String(4813.134),2,"$",0);// result: $ 4,813.13

Функция довольно проста, мы вызываем функцию formatCost()

Если вы просто хотите отформатировать его до 0 десятичных знаков, formatCost(value as string,0)
Если вам нужна валюта, добавьте ее в качестве третьего параметра.
Если вам нужно, чтобы символ был за цифрой, установите позицию в 1
Итак ...

formatCost(String(8/35*100),1,"%",1);// will give "22.9 %"

при желании вы можете добавить больше к формуле, чтобы 5-я переменная могла быть спейсером, чтобы вы могли изменить ее с "," на "." (для французского) или как пробел ""

public function formatCost(v:String, 
           decimal_places:int = 2, 
           currency_symbol:String = "", 
           placement:int = 0){
        v = String(Number(v).toFixed(decimal_places));
        var result:String = new String();
        if(decimal_places == 0){
        }else{
            result = v.substr(-1-decimal_places);
            v = v.substr(0, v.length-1-decimal_places);
        }
        while( v.length > 3 ){
            result = "," + v.substr(-3) + result;
            v = v.substr(0, v.length-3);
        }
        if(v.length > 0){
            if(placement == 0){
                result = currency_symbol + " " + v + result;
            }else if(placement == 1){
                result = v + result + " " + currency_symbol;
            }else{
                result = v + result;
            }
        }
        return result;
    }//closes formatCost
1 голос
/ 25 апреля 2013

Лучшей альтернативой для форматирования валюты является использование класса Adobe flash.globalization.CurrencyFormatter

public static function getDollars(value:Number):String{

        var targetFormatter:CurrencyFormatter = new CurrencyFormatter("en-US");
        return targetFormatter.format(value, true);

    }

Этот класс очень гибкий, что позволяет вам настраивать внешний вид валюты для локали.

0 голосов
/ 24 апреля 2011

Проблема в том, что вы не обращаете внимание на типы переменных.

this.payrollOut - текстовое поле

this.payrollOut.text - текст, содержащийся в этом текстовом поле

this.payroll.value нельзя присвоить текстовое поле или текстовое значение

Таким образом, вы должны преобразовать в ожидаемый тип - в данном случае это Number.

this.payroll.value = Number(this.payrollOut.text);

cf.format также ожидает числовое значение и возвращает строку.

пример использования может быть:

var payrollAmount:Number = 400;
var payrollCurrencyAmount:String = cf.format(payrollAmount);

Есть другие проблемы с кодом, который я вижу - payrollOut не имеет значения - поэтому он все еще не будет функционировать, как ожидалось, но это решает непосредственную проблему.

...