generated from boboko/starter
price function global (needs review)
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { Controller } from '@hotwired/stimulus'
|
||||
import { formatPrice } from '../utils/format-price'
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = ['price', 'image', 'swatch', 'colorName']
|
||||
@@ -30,7 +31,7 @@ export default class extends Controller {
|
||||
if (!variant) return
|
||||
|
||||
if (this.hasPriceTarget && variant.price !== null) {
|
||||
this.priceTarget.textContent = '€' + parseFloat(variant.price).toFixed(2)
|
||||
this.priceTarget.textContent = formatPrice(variant.price)
|
||||
}
|
||||
|
||||
if (this.hasImageTarget && variant.image) {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// Mirrors App\Support\Price::format() — keep both in sync. Greek formatting:
|
||||
// comma as the decimal separator, dot as the thousands separator, and no
|
||||
// decimals shown unless the amount actually needs them.
|
||||
// 19.00 -> "€19", 19.50 -> "€19,5", 19.55 -> "€19,55"
|
||||
export function formatPrice(amount, currency = '€') {
|
||||
if (amount === null || amount === undefined) return null
|
||||
|
||||
const value = Math.round(parseFloat(amount) * 100) / 100
|
||||
const cents = Math.round(value * 100)
|
||||
|
||||
const decimals = cents % 100 === 0 ? 0 : (cents % 10 === 0 ? 1 : 2)
|
||||
|
||||
const formatted = value.toLocaleString('el-GR', {
|
||||
minimumFractionDigits: decimals,
|
||||
maximumFractionDigits: decimals,
|
||||
})
|
||||
|
||||
return currency + formatted
|
||||
}
|
||||
Reference in New Issue
Block a user