求编写AS3的BigNumber/BigInt类:支持超大整数及单位格式化
Got it, let's build this BigInt.as class for you that handles huge integers and formats them using the short-scale naming convention. I’ve structured it to be easy to use and extend, with clear comments so you can follow along.
BigInt.as Class Implementation
We’ll use a string to store the large integer (since native AS3 Number loses precision for values over ~9e15) and include all the features you requested:
package com.utils { public class BigInt { // Private storage for the large integer (string avoids precision loss) private var _value:String; // Short-scale large number units (follows standard short-scale convention) // Each entry maps an exponent (10^x) to its official name private static const UNITS:Array = [ { exponent: 0, name: "" }, { exponent: 3, name: "Thousand" }, { exponent: 6, name: "Million" }, { exponent: 9, name: "Billion" }, { exponent: 12, name: "Trillion" }, { exponent: 15, name: "Quadrillion" }, { exponent: 18, name: "Quintillion" }, { exponent: 21, name: "Sextillion" }, { exponent: 24, name: "Septillion" }, { exponent: 27, name: "Octillion" }, { exponent: 30, name: "Nonillion" }, { exponent: 33, name: "Decillion" }, { exponent: 36, name: "Undecillion" }, { exponent: 39, name: "Duodecillion" }, { exponent: 42, name: "Tredecillion" }, { exponent: 45, name: "Quattuordecillion" }, { exponent: 48, name: "Quindecillion" }, { exponent: 51, name: "Sexdecillion" }, { exponent: 54, name: "Septendecillion" }, { exponent: 57, name: "Octodecillion" }, { exponent: 60, name: "Novemdecillion" }, { exponent: 63, name: "Vigintillion" } ]; // Constructor: accept Number or String (validates input to ensure integer) public function BigInt(value:*):void { if (value is Number) { // Convert number to string, ensure no decimal part var numStr:String = value.toString(); if (numStr.indexOf(".") != -1) { throw new Error("BigInt only accepts integers: " + value); } _value = numStr; } else if (value is String) { // Validate input is a positive integer string if (/^\d+$/.test(value)) { _value = value; } else { throw new Error("Invalid integer string: " + value); } } else { throw new Error("BigInt constructor accepts only Number or String"); } } // Getter for raw integer value as string public function get value():String { return _value; } // Format number to short-scale named format (e.g., "1.54 Million") public function formatToNamedString(decimalPlaces:int = 2):String { if (decimalPlaces < 0) decimalPlaces = 0; var numLength:int = _value.length; var selectedUnit:Object = UNITS[0]; // Find the largest applicable unit for (var i:int = UNITS.length - 1; i >= 0; i--) { if (numLength > UNITS[i].exponent) { selectedUnit = UNITS[i]; break; } } // Calculate scaled value parts var scale:int = selectedUnit.exponent; var integerPart:String = _value.substr(0, numLength - scale); var decimalPart:String = _value.substr(numLength - scale); // Build formatted number var formatted:String = integerPart; if (decimalPlaces > 0 && decimalPart.length > 0) { // Trim decimal to desired length and remove trailing zeros decimalPart = decimalPart.substr(0, decimalPlaces).replace(/0+$/, ""); if (decimalPart.length > 0) { formatted += "." + decimalPart; } } // Append unit name if applicable if (selectedUnit.name !== "") { formatted += " " + selectedUnit.name; } return formatted; } // Optional: Example arithmetic method (addition for large integers) public function add(other:BigInt):BigInt { var a:String = this._value.padStart(Math.max(this._value.length, other._value.length), "0"); var b:String = other._value.padStart(a.length, "0"); var result:String = ""; var carry:int = 0; for (var i:int = a.length - 1; i >= 0; i--) { var sum:int = int(a.charAt(i)) + int(b.charAt(i)) + carry; carry = Math.floor(sum / 10); result = (sum % 10).toString() + result; } if (carry > 0) result = carry.toString() + result; return new BigInt(result); } } }
Key Features Breakdown
- Huge Integer Support: Storing values as strings lets us handle integers of any length without losing precision, which solves the problem of native
Numberlimitations. - Short-Scale Formatting: The
UNITSarray covers all standard short-scale names up to Vigintillion (10^63). TheformatToNamedStringmethod automatically picks the right unit and cleans up trailing decimal zeros for a polished output. - Input Validation: The constructor ensures only valid integers are accepted, preventing invalid data from breaking your code.
- Extensible Arithmetic: I included an
addmethod as an example—you can easily extend this with multiplication, subtraction, or comparison methods if needed.
Usage Example
Here’s how to use the class in your project:
import com.utils.BigInt; // Create a BigInt from a string (for numbers too large for native Number) var largeSales:BigInt = new BigInt("154200000"); trace(largeSales.formatToNamedString()); // Output: "154.2 Million" // Format a Vigintillion-scale number var cosmicNum:BigInt = new BigInt("19800000000000000000000000000000000000000000000000000000000000"); trace(cosmicNum.formatToNamedString(2)); // Output: "1.98 Vigintillion" // Add two large integers var num1:BigInt = new BigInt("999999999999999999"); var num2:BigInt = new BigInt("2"); var total:BigInt = num1.add(num2); trace(total.value); // Output: "1000000000000000001" trace(total.formatToNamedString()); // Output: "1 Trillion"
Quick Notes
- If you need negative integers, add a private
_isNegativeflag to the class and update the constructor, formatting, and arithmetic methods to handle signs. - The
formatToNamedStringmethod uses 2 decimal places by default, but you can pass any number (including 0) to adjust precision.
内容的提问来源于stack exchange,提问作者NAMAssist
相关产品推荐
相关产品推荐

